Knuth shuffle: Difference between revisions

 
(41 intermediate revisions by 22 users not shown)
Line 53:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F knuth_shuffle(&x)
L(i) (x.len - 1 .< 0).step(-1)
V j = random:(0..i)
Line 60:
V x = Array(0..9)
knuth_shuffle(&x)
print(‘shuffled: ’x)</langsyntaxhighlight>
 
{{out}}
Line 69:
=={{header|360 Assembly}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="360asm">
* Knuth shuffle 02/11/2015
KNUTHSH CSECT
Line 119:
YREGS
END KNUTHSH
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 129:
Runs on easy6502, which has a random number generated memory-mapped at zero page address <code>$FE</code> that updates after every instruction. Works on any array size up to and including 256 bytes. (The code I wrote here prior to this edit was much faster but only worked on arrays of exactly 256 bytes in size). The reason for this was that constraining a random number generator that can produce any 8-bit value to a subset is tricky, since just "rolling again" if out of range will eventually cause the program to lock up if it can't produce a value in range purely by chance. This method uses a bit mask that shifts right as the loop counter decreases to zero, which means that even when only a few bytes still need to be shuffled, the routine is just as quick as it was at the beginning.
 
<langsyntaxhighlight lang="6502asm">define sysRandom $fe
define tempMask $ff
define range $00
Line 197:
 
end:
brk</langsyntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program knuthshuffle64.s */
Line 343:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">:set-state-ok t
 
(defun array-swap (name array i j)
Line 369:
array
(1- (first (dimensions name array)))
state))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintTable(INT ARRAY tab BYTE size)
BYTE i
 
Line 414:
PrintE("Shuffled data:")
PrintTable(tab,size)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Knuth_shuffle.png Screenshot from Atari 8-bit computer]
Line 427:
=={{header|Ada}}==
This implementation is a generic shuffle routine, able to shuffle an array of any type.
<langsyntaxhighlight Adalang="ada">generic
type Element_Type is private;
type Array_Type is array (Positive range <>) of Element_Type;
procedure Generic_Shuffle (List : in out Array_Type);</langsyntaxhighlight>
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
 
procedure Generic_Shuffle (List : in out Array_Type) is
Line 448:
List(K) := T;
end loop;
end Generic_Shuffle;</langsyntaxhighlight>
An example using Generic_Shuffle.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Generic_Shuffle;
 
Line 471:
Ada.Text_IO.Put(Integer'Image(Integer_List(I)));
end loop;
end Test_Shuffle;</langsyntaxhighlight>
 
=={{header|Aime}}==
The shuffle function works on any type (the lists are heterogenous).
<langsyntaxhighlight lang="aime">void
shuffle(list l)
{
Line 488:
}
}
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G}}
<langsyntaxhighlight lang="algol68">PROC between = (INT a, b)INT :
(
ENTIER (random * ABS (b-a+1) + (a<b|a|b))
Line 505:
a[j] := t
OD
);</langsyntaxhighlight>
<langsyntaxhighlight lang="algol68">main:(
[20]INT a;
FOR i FROM 1 TO 20 DO a[i] := i OD;
knuth shuffle(a);
print(a)
)</langsyntaxhighlight>
 
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
v={},n=19
'0,1,2,3,4,5,6,7,8,9,"\t","\v","\v","A","B","C","D","E","F"' enlistar en 'v'
imprimir ("Original:\n[",v,"]\n\n")
imprimir (rareti( n, #(ceil(rand(n))), n, intercambiar en (v)),\
"Processed:\n[", v,"]\n" )
terminar
</syntaxhighlight>
{{out}}
<pre>
Original:
[0,1,2,3,4,5,6,7,8,9, ,
,
,A,B,C,D,E,F]
 
Processed:
[F,B, ,1,9,
,2,D,5,6,4,8,C,7,A,
,3,0,E]
</pre>
 
=={{header|AppleScript}}==
Line 517 ⟶ 545:
===Iteration===
 
<langsyntaxhighlight AppleScriptlang="applescript">set n to 25
 
set array to {}
Line 530 ⟶ 558:
end repeat
 
return {unshuffled, shuffled}</langsyntaxhighlight>
Example:
<langsyntaxhighlight AppleScriptlang="applescript">{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25},
{14, 25, 3, 1, 12, 18, 11, 20, 16, 15, 21, 5, 22, 19, 2, 24, 8, 10, 13, 6, 17, 23, 9, 7, 4}}</langsyntaxhighlight>
 
----
Better:
<langsyntaxhighlight lang="applescript">-- Fisher-Yates (aka Durstenfeld, aka Knuth) shuffle.
on shuffle(theList, l, r)
set listLength to (count theList)
Line 561 ⟶ 589:
set array to {"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike"}
-- Shuffle all items (1 thru -1).
shuffle(array, 1, -1)</langsyntaxhighlight>
 
{{output}}
''eg.''
<langsyntaxhighlight lang="applescript">{"Golf", "Foxtrot", "Echo", "Delta", "Kilo", "Charlie", "Mike", "Alpha", "Lima", "Juliett", "India", "Bravo", "Hotel"}</langsyntaxhighlight>
 
When a large number of random indices is required, it can actually be faster to create a list of integers and select from these using AppleScript's 'some' specifier than to call the StandardAdditions' 'random number' function repeatedly. But a better solution since Mac OS X 10.11 is to use the system's GameplayKit framework:
<langsyntaxhighlight lang="applescript">use AppleScript version "2.5" -- OS X 10.11 (El Capitan) or later
use framework "Foundation"
use framework "GameplayKit"
Line 591 ⟶ 619:
return theList
end shuffle</langsyntaxhighlight>
----
 
===Functional composition===
 
<langsyntaxhighlight AppleScriptlang="applescript">-- KNUTH SHUFFLE -------------------------------------------------------------
 
-- knuthShuffle :: [a] -> [a]
Line 667 ⟶ 695:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
e.g.
<langsyntaxhighlight AppleScriptlang="applescript">{"mu", "theta", "alpha", "delta", "zeta", "gamma",
"iota", "kappa", "lambda", "epsilon", "beta", "eta"}</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 908 ⟶ 936:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">knuth: function [arr][
if 0=size arr -> return []
Line 928 ⟶ 956:
print knuth [10]
print knuth [10 20]
print knuth [10 20 30]</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=133 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
 
Line 944 ⟶ 972:
s .= "," . a%A_Index%
Return SubStr(s,2) ; drop leading comma
}</langsyntaxhighlight>
 
For Arrays:
Line 951 ⟶ 979:
 
[https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array#6274381 (translated from)]
<langsyntaxhighlight AutoHotkeylang="autohotkey">toShuffle:=[1,2,3,4,5,6]
shuffled:=shuffle(toShuffle)
;p(toShuffle) ;because it modifies the original array
Line 967 ⟶ 995:
}
return a
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
Dim $a[10]
ConsoleWrite('array before permutation:' & @CRLF)
Line 996 ⟶ 1,024:
Next
EndFunc
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,010 ⟶ 1,038:
This example shows how to shuffle such arrays.
The elements can be integers, floating-point numbers, or strings.
<langsyntaxhighlight lang="awk"># Shuffle an _array_ with indexes from 1 to _len_.
function shuffle(array, len, i, j, t) {
for (i = len; i > 1; i--) {
Line 1,030 ⟶ 1,058:
for (i = 1; i < len; i++) printf "%s ", array[i]
printf "%s\n", array[len]
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="qbasic">RANDOMIZE TIMER
 
DIM cards(51) AS INTEGER
Line 1,053 ⟶ 1,081:
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT
PRINT</langsyntaxhighlight>
 
{{out}}
Line 1,067 ⟶ 1,095:
==={{header|Applesoft BASIC}}===
As mentioned in the Sinclair ZX81 BASIC solution, for very small positive integer values, a string is a much more memory-efficient array, but here is an example of an array with numbers. Line <code>150</code> initializes and prints each element in the array. Line <code>190</code> performs the swap of the elements.
<langsyntaxhighlight lang="basic"> 100 :
110 REM KNUTH SHUFFLE
120 :
Line 1,079 ⟶ 1,107:
200 FOR I = 1 TO 25
210 PRINT A(I);" ";: NEXT I
220 END</syntaxhighlight>
</lang>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1
Line 1,087 ⟶ 1,114:
<pre>20 5 6 9 15 23 22 8 4 24 7 11 16 21 2 17
14 10 19 13 12 18 1 3 25</pre>
 
==={{header|OxygenBasic}}===
<lang>
uses chaos
uses timeutil
seed=GetTickCount
int i,j
int d[100] 'int array or any other type
...
for i=100 to 1 step-1
j=irnd(1,100)
swap d[i],d[j]
next
</lang>
 
==={{header|Sinclair ZX81 BASIC}}===
For very small positive integer values, a string (which can be treated as an array of bytes) is much more memory-efficient than an array of numbers. In this program we shuffle a string consisting of the letters 'A' to 'Z'. The ZX81 is slow enough that we can watch the shuffle happening in real time, with items switching to inverse video display as they are shuffled. (This can be done, in the ZX81 character set, by setting the high bit in the character code.) Line <code>10</code> seeds the pseudo-random number generator. Note that strings (and arrays) are indexed from 1.
 
The program works with the unexpanded (1k RAM) ZX81.
<lang basic> 10 RAND
20 LET A$=""
30 FOR I=1 TO 26
40 LET A$=A$+CHR$ (37+I)
50 NEXT I
60 PRINT A$
70 FOR I=26 TO 2 STEP -1
80 LET J=1+INT (RND*I)
90 LET T$=A$(I)
100 LET A$(I)=A$(J)
110 LET A$(J)=T$
120 PRINT AT 0,I-1;CHR$ (CODE A$(I)+128)
130 PRINT AT 0,J-1;CHR$ (CODE A$(J)+128)
140 NEXT I</lang>
{{out}}
While the program is running, we will see something like this (using lower case as a stand-in for inverse video):
<pre>ABCuEFGzwJKLMNOPxySvdtiqrh</pre>
When it has finished, the screen will show (for example):
<pre>lcjbpxekzsaygumwnovfdtiqrh</pre>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> cards% = 52
DIM pack%(cards%)
FOR I% = 1 TO cards%
Line 1,138 ⟶ 1,127:
PRINT pack%(I%);
NEXT I%
PRINT</langsyntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">100 CLS
110 RANDOMIZE TIMER
120 DIM CARDS(51)
130 PRINT "before:"
140 FOR L0 = 0 TO 51
150 CARDS(L0) = L0
160 PRINT STR$(CARDS(L0));" ";
170 NEXT L0
180 FOR L0 = 51 TO 0 STEP -1
190 CARD = INT(RND(1)*(L0+1))
200 IF CARD <> L0 THEN T = CARDS(CARD) : CARDS(CARD) = CARDS(L0) : CARDS(L0) = T
210 NEXT L0
220 PRINT : PRINT
230 PRINT "after:"
240 FOR L0 = 0 TO 51
250 PRINT STR$(CARDS(L0));" ";
260 NEXT L0
270 PRINT
280 END</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Shuffle.bas"
110 RANDOMIZE
120 NUMERIC ARRAY(1 TO 20)
Line 1,164 ⟶ 1,181:
310 IF CARD<>I THEN LET T=A(CARD):LET A(CARD)=A(I):LET A(I)=T
320 NEXT
330 END DEF</langsyntaxhighlight>
 
==={{header|QB64Minimal BASIC}}===
<syntaxhighlight lang="qbasic">100 REM Knuth shuffle
<lang QB64>
110 RANDOMIZE
shuffle and make sure that number does not take its place
120 DIM B(51)
and between cells at least 10% ... Shuffle from Russia
130 PRINT "BEFORE:"
140 FOR L0 = 0 TO 51
150 LET B(L0) = L0
160 PRINT B(L0);" ";
170 NEXT L0
180 FOR L0 = 51 TO 0 STEP -1
190 LET C = INT(RND*(L0+1))
200 IF C <> L0 THEN 220
210 GOTO 250
220 LET T = B(C)
230 LET B(C) = B(L0)
240 LET B(L0) = T
250 NEXT L0
260 PRINT
270 PRINT
280 PRINT "AFTER:"
290 FOR L0 = 0 TO 51
300 PRINT B(L0);" ";
310 NEXT L0
320 PRINT
330 END</syntaxhighlight>
 
==={{header|OxygenBasic}}===
<syntaxhighlight lang="text">uses chaos
uses timeutil
seed=GetTickCount
int i,j
int d[100] 'int array or any other type
...
for i=100 to 1 step -1
j=irnd(1,100)
swap d[i],d[j]
next</syntaxhighlight>
 
==={{header|QB64}}===
Shuffle and make sure that number does not take its place<br/>
and between cells at least 10% ... Shuffle from Russia
<syntaxhighlight lang="qbasic">
a = 100: DIM d(a): x=0: k=0: t$=CHR$(9): RANDOMIZE TIMER 'Shuffle_RUS.bas
PRINT ,: FOR i = 1 TO a: d(i)=i: NEXT
Line 1,194 ⟶ 1,248:
IF d(i) = i THEN PRINT -d(i); ELSE PRINT d(i);
NEXT
WEND: PRINT: PRINT " = "; k, TIMER-z: END</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
For very small positive integer values, a string (which can be treated as an array of bytes) is much more memory-efficient than an array of numbers. In this program we shuffle a string consisting of the letters 'A' to 'Z'. The ZX81 is slow enough that we can watch the shuffle happening in real time, with items switching to inverse video display as they are shuffled. (This can be done, in the ZX81 character set, by setting the high bit in the character code.) Line <code>10</code> seeds the pseudo-random number generator. Note that strings (and arrays) are indexed from 1.
 
The program works with the unexpanded (1k RAM) ZX81.
<syntaxhighlight lang="basic"> 10 RAND
20 LET A$=""
30 FOR I=1 TO 26
40 LET A$=A$+CHR$ (37+I)
50 NEXT I
60 PRINT A$
70 FOR I=26 TO 2 STEP -1
80 LET J=1+INT (RND*I)
90 LET T$=A$(I)
100 LET A$(I)=A$(J)
110 LET A$(J)=T$
120 PRINT AT 0,I-1;CHR$ (CODE A$(I)+128)
130 PRINT AT 0,J-1;CHR$ (CODE A$(J)+128)
140 NEXT I</syntaxhighlight>
{{out}}
While the program is running, we will see something like this (using lower case as a stand-in for inverse video):
<pre>ABCuEFGzwJKLMNOPxySvdtiqrh</pre>
When it has finished, the screen will show (for example):
<pre>lcjbpxekzsaygumwnovfdtiqrh</pre>
 
==={{header|True BASIC}}===
{{trans|BASIC}}
<syntaxhighlight lang="qbasic">OPTION BASE 0
RANDOMIZE
 
DIM cards(51)
 
PRINT "before:"
FOR L0 = 0 TO 51
LET cards(L0) = L0
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT L0
 
FOR L0 = 51 TO 0 STEP -1
LET card = INT(RND * (L0 + 1))
IF card <> L0 THEN
LET t = cards(lb + L0)
LET cards(lb + L0) = cards(lb + card)
LET cards(lb + card) = t
END IF
NEXT L0
 
PRINT
PRINT "after:"
FOR L0 = 0 TO 51
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT L0
END</syntaxhighlight>
{{out}}
<pre>Same as BASIC entry.</pre>
 
=={{header|bc}}==
Line 1,201 ⟶ 1,310:
This code requires a <tt>bc</tt> with long names; the test program also requires a <tt>bc</tt> with the <tt>print</tt> statement.
{{works with|OpenBSD bc}}
<langsyntaxhighlight lang="bc">seed = 1 /* seed of the random number generator */
scale = 0
 
Line 1,244 ⟶ 1,353:
trash = shuffle(10)
"Shuffled array: "; trash = print_array(10)
quit</langsyntaxhighlight>
{{out}}
<pre>Original array: 11, 22, 33, 44, 55, 66, 77, 88, 99, 110
Line 1,253 ⟶ 1,362:
BQN's arrays are immutable, but variable values can be changed using the `↩` symbol. This program repeatedly changes the array's value using under.
 
<langsyntaxhighlight lang="bqn">Knuth ← {
𝕊 arr:
l ← ≠arr
Line 1,266 ⟶ 1,375:
P ⟨10⟩
P ⟨10, 20⟩
P ⟨10, 20, 30⟩</langsyntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=S251dGgg4oaQIHsKICDwnZWKIGFycjoKICBsIOKGkCDiiaBhcnIKICB7CiAgICBhcnIg4oapIOKMveKMvijin6jigKJyYW5kLlJhbmdlIGwsIPCdlanin6niirjiio8pYXJyCiAgfcKo4oaVbAogIGFycgp9ClAg4oaQIOKAolNob3cgS251dGgKClAg4p+o4p+pClAg4p+oMTDin6kKUCDin6gxMCwgMjDin6kKUCDin6gxMCwgMjAsIDMw4p+p Try It!]
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">shuffle = { a |
(a.length - 1).to 1 { i |
random_index = random(0, i)
Line 1,282 ⟶ 1,391:
}
 
p shuffle [1 2 3 4 5 6 7]</langsyntaxhighlight>
 
=={{header|C}}==
This shuffles any "object"; it imitates <tt>qsort</tt> in the syntax.
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
 
Line 1,306 ⟶ 1,415:
}
free(temp);
} </langsyntaxhighlight>
Alternatively, using Durstenfeld's method (swapping selected item and last item in each iteration instead of literally shifting everything), and macro'd function declaration/definition:
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,359 ⟶ 1,468:
printf(" %d", x[i]);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">public static void KnuthShuffle<T>(T[] array)
{
System.Random random = new System.Random();
Line 1,370 ⟶ 1,479:
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
'''Compiler:''' [[g++]] (version 4.3.2 20081105 (Red Hat 4.3.2-7))
<langsyntaxhighlight lang="cpp" line="1">#include <cstdlib>
#include <algorithm>
#include <iterator>
Line 1,380 ⟶ 1,489:
template<typename RandomAccessIterator>
void knuthShuffle(RandomAccessIterator begin, RandomAccessIterator end) {
if(begin == end) {
return;
}
for(unsigned int n = end - begin - 1; n >= 1; --n) {
unsigned int k = rand() % (n + 1);
Line 1,386 ⟶ 1,498:
}
}
}</langsyntaxhighlight>
The standard library provides this in the form of <code>std::random_shuffle</code>.
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <vector>
 
Line 1,398 ⟶ 1,510:
std::random_shuffle(array, array + 9); // shuffle C-style array
std::random_shuffle(vec.begin(), vec.end()); // shuffle STL container
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn shuffle [vect]
(reduce (fn [v i] (let [r (rand-int i)]
(assoc v i (v r) r (v i))))
vect (range (dec (count vect)) 1 -1)))</langsyntaxhighlight>
This works by generating a sequence of end-indices from n-1 to 1, then reducing that sequence (starting with the original vector) through a function that, given a vector and end-index, performs a swap between the end-index and some random index less than the end-index.
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">knuth_shuffle = proc [T: type] (a: array[T])
lo: int := array[T]$low(a)
hi: int := array[T]$high(a)
Line 1,428 ⟶ 1,540:
stream$puts(po, int$unparse(i) || " ")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>7 9 2 3 4 8 1 6 5</pre>
Line 1,434 ⟶ 1,546:
 
=={{header|CMake}}==
<langsyntaxhighlight lang="cmake"># shuffle(<output variable> [<value>...]) shuffles the values, and
# stores the result in a list.
function(shuffle var)
Line 1,466 ⟶ 1,578:
endforeach(i)
set("${var}" ${answer} PARENT_SCOPE)
endfunction(shuffle)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="cmake">shuffle(result 11 22 33 44 55 66)
message(STATUS "${result}")
# One possible output:
# -- 66;33;22;55;44;11</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. knuth-shuffle.
 
Line 1,502 ⟶ 1,614:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="coffeescript">knuth_shuffle = (a) ->
n = a.length
while n > 1
Line 1,526 ⟶ 1,638:
 
for key, val of counts
console.log "#{key}: #{val}"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,539 ⟶ 1,651:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun nshuffle (sequence)
(loop for i from (length sequence) downto 2
do (rotatef (elt sequence (random i))
(elt sequence (1- i))))
sequence)</langsyntaxhighlight>
This operates on arbitrary sequences, but will be inefficient applied to a list as opposed to a vector. Dispatching on type, and using an intermediate vector to hold the contents of list can make both cases more efficient (since the array specific case can use <code>aref</code> rather than <code>elt</code>):
<langsyntaxhighlight lang="lisp">(defun nshuffle (sequence)
(etypecase sequence
(list (nshuffle-list sequence))
Line 1,560 ⟶ 1,672:
do (rotatef (aref array (random i))
(aref array (1- i)))
finally (return array)))</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">def knuthShuffle(items : Array)
i = items.size-1
while i > 1
Line 1,571 ⟶ 1,683:
i -= 1
end
end</langsyntaxhighlight>
 
=={{header|D}}==
===Standard Version===
A variant of the Knuth shuffle is in the D standard library Phobos:
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.random;
 
Line 1,582 ⟶ 1,694:
a.randomShuffle;
a.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[8, 9, 3, 1, 7, 5, 4, 6, 2]</pre>
Line 1,588 ⟶ 1,700:
===One Implementation===
This shuffles any collection that supports random access, length and swapping of items:
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.random, std.range;
 
void knuthShuffle(Range)(Range r)
Line 1,601 ⟶ 1,713:
a.knuthShuffle;
a.writeln;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 1,607 ⟶ 1,719:
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">procedure KnuthShuffle(a : array of Integer);
var
i, j, tmp : Integer;
Line 1,615 ⟶ 1,727:
tmp:=a[i]; a[i]:=a[j]; a[j]:=tmp;
end;
end;</langsyntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def shuffle(array, random) {
for bound in (2..(array.size())).descending() {
def i := random.nextInt(bound)
Line 1,626 ⟶ 1,738:
array[i] := t
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="e">? def arr := [1,2,3,4,5,6,7,8,9,10].diverge()
# value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].diverge()
 
? shuffle(arr, entropy)
? arr
# value: [4, 5, 2, 9, 7, 8, 1, 3, 6, 10].diverge()</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
<lang>func shuffle . a[] .
proc shuffle . a[] .
for i = len a[] downto 2
for ri = randomlen ia[] downto 2
swap a[ r] a[i= -randint 1]i
swap a[r] a[i]
.
.
.
arr[] = [ 1 2 3 ]
call shuffle arr[]
print arr[]
</syntaxhighlight>
</lang>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
Remark- The native '''shuffle''' function implementation in EchoLisp has been replaced by this one.
Thx Rosetta Code.
Line 1,677 ⟶ 1,790:
'(adrien 🎸 alexandre 🚂 antoine 🍼 ben 📚 georges 📷 julie 🎥 marine 🐼 nathalie 🍕 ))
→ (antoine 🎥 🚂 marine adrien nathalie 🍼 🍕 ben 🐼 julie 📷 📚 🎸 alexandre georges)
</syntaxhighlight>
</lang>
 
=={{header|Egel}}==
<syntaxhighlight lang="egel">
<lang Egel>
import "prelude.eg"
import "random.ego"
Line 1,698 ⟶ 1,811:
 
def main = shuffle (fromto 1 9)
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,758 ⟶ 1,871:
end
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,766 ⟶ 1,879:
 
=={{header|Elena}}==
ELENA 46.x:
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 1,778 ⟶ 1,891:
var max := self.Length;
for(int i := 0,; i < max,; i += 1)
{
var j := randomGenerator.evalnextInt(i,max);
self.exchange(i,j)
Line 1,791 ⟶ 1,904:
public program()
{
var a := Array.allocate:(MAX).populate::(i => i );
console.printLine(a.randomize())
}</langsyntaxhighlight>
{{out}}
<pre>
7,3,6,8,4,9,05,1,2,56,0,7,9
</pre>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Knuth do
def shuffle( inputs ) do
n = length( inputs )
Line 1,823 ⟶ 1,936:
Map.update(acc, k, 1, &(&1+1))
end)
|> Enum.each(fn {k,v} -> IO.inspect {k,v} end)</langsyntaxhighlight>
 
{{out}}
Line 1,837 ⟶ 1,950:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( knuth_shuffle ).
 
Line 1,852 ⟶ 1,965:
Item = lists:nth( random:uniform(N), Inputs ),
{lists:delete(Item, Inputs), [Item | Acc]}.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,860 ⟶ 1,973:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM KNUTH_SHUFFLE
 
CONST CARDS%=52
Line 1,879 ⟶ 1,992:
PRINT
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{trans|BASIC}}
<langsyntaxhighlight Euphorialang="euphoria">sequence cards
cards = repeat(0,52)
integer card,temp
Line 1,905 ⟶ 2,018:
for i = 1 to 52 do
printf(1,"%d ",cards[i])
end for</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
Line 1,911 ⟶ 2,024:
 
This is the original Fisher-Yates shuffle as described by the link:
<langsyntaxhighlight lang="fsharp">open System
 
let FisherYatesShuffle (initialList : array<'a>) = // '
Line 1,927 ⟶ 2,040:
initialList.[index] // and return the original item
seq {(initialList.Length) .. -1 .. 1} // Going from the length of the list down to 1
|> Seq.map (fun i -> nextItem i) // yield the next item</langsyntaxhighlight>
Here's the modified Knuth shuffle which shuffles the original array in place
<langsyntaxhighlight lang="fsharp">let KnuthShuffle (lst : array<'a>) = // '
let Swap i j = // Standard swap
let item = lst.[i]
Line 1,938 ⟶ 2,051:
[0..(ln - 2)] // For all indices except the last
|> Seq.iter (fun i -> Swap i (rnd.Next(i, ln))) // swap th item at the index with a random one following it (or itself)
lst // Return the list shuffled in place</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="fsharp">> KnuthShuffle [| "Darrell"; "Marvin"; "Doug"; "Greg"; "Sam"; "Ken" |];;
val it : string array = [|"Marvin"; "Doug"; "Sam"; "Darrell"; "Ken"; "Greg"|]</langsyntaxhighlight>
 
=={{header|Factor}}==
There is a <code>randomize</code> word already in the standard library. Implementation:
<langsyntaxhighlight lang="factor">: randomize ( seq -- seq )
dup length [ dup 1 > ]
[ [ iota random ] [ 1 - ] bi [ pick exchange ] keep ]
while drop ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">class Main
{
static Void knuthShuffle (List array)
Line 1,972 ⟶ 2,085:
echo (b)
}
}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">include random.fs
 
: shuffle ( deck size -- )
Line 1,989 ⟶ 2,102:
create deck 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,
 
deck 10 2dup shuffle .array</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Knuth_Shuffle
implicit none
 
Line 2,025 ⟶ 2,138:
end subroutine Shuffle
end program Knuth_Shuffle</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 22-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 2,104 ⟶ 2,217:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Starting array
Line 2,124 ⟶ 2,237:
=={{header|Frink}}==
The built-in method <CODE><I>array</I>.shuffle[]</CODE> implements the Fisher-Yates-Knuth shuffle algorithm:
<langsyntaxhighlight lang="frink">
a = [1,2,3]
a.shuffle[]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def shuffle( a ) =
res = array( a )
n = a.length()
Line 2,138 ⟶ 2,251:
res(i), res(r) = res(r), res(i)
res.toList()</langsyntaxhighlight>
 
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn KnuthShuffle( mutArr as CFMutableArrayRef )
NSUInteger i, j, count
count = len(mutArr)
for i = count-1 to 1 step -1
j = rnd(i+1)-1
MutableArrayExchangeObjects( mutArr, i, j )
next
end fn
 
randomize
 
CFMutableArrayRef mutArr
NSUInteger i
mutArr = fn MutableArrayWithObjects( @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, NULL )
NSLog( @"Before shuffle: %@", fn ArrayComponentsJoinedByString( mutArr, @"" ) )
 
for i = 1 to 100
fn KnuthShuffle( mutArr )
NSLog( @"%@", fn ArrayComponentsJoinedByString( mutArr, @"" ) )
next
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Before shuffle: 0123456789
1274860395
2715638904
7182035964
1297658403
2916574083
9162507843
1875962034
8721965034
7968402351
9347510862
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=58402023fbdc617ce10f6a85db721105 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim iTotal As Integer = 40
Dim iCount, iRand1, iRand2 As Integer
Line 2,167 ⟶ 2,325:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 2,175 ⟶ 2,333:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Return the list L after applying Knuth shuffle. GAP also has the function Shuffle, which does the same.
ShuffleAlt := function(a)
local i, j, n, t;
Line 2,200 ⟶ 2,358:
# One may also call the built-in random generator on the symmetric group :
Random(SymmetricGroup(10));
(1,8,2,5,9,6)(3,4,10,7)</langsyntaxhighlight>
 
=={{header|Go}}==
Line 2,208 ⟶ 2,366:
implementing a Fisher–Yates shuffle.)
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,229 ⟶ 2,387:
}
fmt.Println(a)
}</langsyntaxhighlight>
To shuffle any type:
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,278 ⟶ 2,436:
shuffle(a)
fmt.Println(a)
}</langsyntaxhighlight>
{{out|Example output}} (of either program)
<pre>
Line 2,287 ⟶ 2,445:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def shuffle = { list ->
if (list == null || list.empty) return list
def r = new Random()
Line 2,296 ⟶ 2,454:
}
list
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">def list = [] + (0..20)
println list
println shuffle(list)
println shuffle(list)
println shuffle(list)</langsyntaxhighlight>
{{out}}
<pre>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Line 2,310 ⟶ 2,468:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import System.Random (randomRIO)
 
mkRands :: Int -> IO [Int]
Line 2,326 ⟶ 2,484:
 
knuthShuffle :: [a] -> IO [a]
knuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> mkRands (length xs)</langsyntaxhighlight>
 
or, as an alternative to making two indexed references into the list with '''(!!)''':
<langsyntaxhighlight lang="haskell">import System.Random (randomRIO)
import Data.Bool (bool)
 
Line 2,350 ⟶ 2,508:
 
main :: IO ()
main = knuthShuffle ['a' .. 'k'] >>= print</langsyntaxhighlight>
 
Examples of use of either of the two versions above:
Line 2,359 ⟶ 2,517:
[(0,10),(8,18),(2,12),(3,13),(9,19),(4,14),(7,17),(1,11),(6,16),(5,15)]</pre>
Function for showing intermediate results:
<langsyntaxhighlight Haskelllang="haskell">knuthShuffleProcess :: (Show a) => [a] -> IO ()
knuthShuffleProcess =
(mapM_ print. reverse =<<). ap (fmap. (. zip [1..]). scanr swapElems) (mkRands. length)</langsyntaxhighlight>
{{out}} Detailed example:
<pre>*Main> knuthShuffleProcess ['a'..'k']
Line 2,376 ⟶ 2,534:
"iebjhkcgfad"</pre>
An imperative implementation using arrays and the <code>ST</code> monad:
<langsyntaxhighlight lang="haskell">import Data.Array.ST
import Data.STRef
import Control.Monad
Line 2,396 ⟶ 2,554:
where len = length list
newAry :: (Int, Int) -> [a] -> ST s (STArray s Int a)
newAry = newListArray</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The <tt>shuffle</tt> method used here can shuffle lists, record fields, and strings:
<langsyntaxhighlight lang="icon">procedure main()
show(shuffle([3,1,4,1,5,9,2,6,3]))
show(shuffle("this is a string"))
Line 2,413 ⟶ 2,571:
every writes(!A," ")
write()
end</langsyntaxhighlight>
{{out}}
<pre>->ks
Line 2,420 ⟶ 2,578:
-></pre>
Note that the gloriously succinct 'standard' Icon shuffle:
<langsyntaxhighlight lang="icon">procedure shuffle(A)
every !A :=: ?A
end</langsyntaxhighlight>
is subtly biased.
 
=={{header|Inform 6}}==
<langsyntaxhighlight Informlang="inform 6">[ shuffle a n i j tmp;
for (i = n - 1: i > 0: i--) {
j = random(i + 1) - 1;
{
j = random(i + 1) - 1;
 
tmp = a->j;
a->j = a->i;
a->i = tmp;
}
];</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">KS=:{~ (2&{.@[ {`(|.@[)`]} ])/@(,~(,.?@>:))@i.@#</langsyntaxhighlight>
The input array is transformed to a rectangular array of indexes. By doing this all kinds of arrays can serve as input (see examples below). The process is imitated by using using a fold, swapping elements in a restricted part of this index-array in each fold step.
<langsyntaxhighlight lang="j">process J
 
fold swap transform array <==> f / g y</langsyntaxhighlight>
Example of a transformed input:
<langsyntaxhighlight lang="j">(,~(,.?@>:))@i.@# 1+i.6
0 0 0 0 0 0
1 1 0 0 0 0
Line 2,451 ⟶ 2,608:
4 3 0 0 0 0
5 0 0 0 0 0
0 1 2 3 4 5</langsyntaxhighlight>
The last row is the index-array that has to be shuffled. The other rows have valid indexes in the first two columns. The second column has a randomized value <= value first column.
 
The index-swapping is done by the part:
<langsyntaxhighlight lang="j">2&{.@[ {`(|.@[)`]} ]</langsyntaxhighlight>
Finally, the shuffled indexes select elements from the original array.
<syntaxhighlight lang ="j">input { ~ shuffled indexes</langsyntaxhighlight>
Alternatively, instead of creating a rectangular array, the swapping indices and the original data can be individually boxed.
 
Line 2,463 ⟶ 2,620:
 
With this approach, the data structure with the swapping indices and the original data could look like this:
<langsyntaxhighlight lang="j"> (|.@; ;&~./@(,. ?@>:)@i.@#)'abcde'
+---+-+---+---+-+-----+
|4 2|3|2 1|1 0|0|abcde|
+---+-+---+---+-+-----+</langsyntaxhighlight>
Note that we have the original data here, instead of indices to select all of its items. Note also that we have only a single value in a box where an item is being "swapped" with itself (this is required by J's cycle operation (<code>C.</code>)).
 
The resulting definition looks like this:
<langsyntaxhighlight lang="j">KS=: [: > (<@C. >)/@(|.@; ;&~./@(,. ?@>:)@i.@#)</langsyntaxhighlight>
Note that here we did not wind up with a list of indices which we used to permute the original data set. That data set is permuted directly. However, it is in a box and we do have to remove it from that box.
 
Permuting the data directly, instead of permuting indices, has performance implications when the items being swapped are large, but see the note at the end of this entry for J for how you would do this operation in a "real" J program.
 
Examples:<langsyntaxhighlight lang="j">]A=: 5+i.9
5 6 7 8 9 10 11 12 13</langsyntaxhighlight> Shuffle:
<langsyntaxhighlight lang="j">KS A
13 10 7 5 11 9 8 6 12</langsyntaxhighlight>Input
<langsyntaxhighlight lang="j">]M=: /:~(1 2 3,:2 3 4),(11 2 3,: 0 11 2),(1 1 1,:1 0),:1 1 1,:1 0 1
1 1 1
1 0 0
Line 2,490 ⟶ 2,647:
 
11 2 3
0 11 2</langsyntaxhighlight>Shuffle
<langsyntaxhighlight lang="j">KS M
11 2 3
0 11 2
Line 2,502 ⟶ 2,659:
 
1 2 3
2 3 4</langsyntaxhighlight>Input
<langsyntaxhighlight lang="j">]L=:'aA';'bbB';'cC%$';'dD@'
+--+---+----+---+
|aA|bbB|cC%$|dD@|
+--+---+----+---+</langsyntaxhighlight>Shuffle
<langsyntaxhighlight lang="j">KS L
+--+----+---+---+
|aA|cC%$|dD@|bbB|
+--+----+---+---+</langsyntaxhighlight>
In J the shuffling of an arbitrary array can easily be implemented by the phrase
( ref http://www.jsoftware.com/jwiki/JPhrases/RandomNumbers ):
<syntaxhighlight lang ="j">({~?~@#)</langsyntaxhighlight>
Applied on the former examples:
<langsyntaxhighlight lang="j">({~?~@#) A
8 7 13 6 10 11 5 9 12
 
Line 2,534 ⟶ 2,691:
+----+---+--+---+
|cC%$|bbB|aA|dD@|
+----+---+--+---+</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Random;
 
public static final Random gen = new Random();
Line 2,560 ⟶ 2,717:
array[k] = temp;
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,566 ⟶ 2,723:
===ES5===
 
<langsyntaxhighlight lang="javascript">function knuthShuffle(arr) {
var rand, temp, i;
 
for (i = arr.length - 1; i > 0; i -= 1) {
rand = Math.floor((i + 1) * Math.random());//get random between zero and i (inclusive)
temp = arr[rand];//swap i and the zero-indexed number
arr[rand] = arr[i]; //swap i (last element) with random element.
arr[i] = temp;
}
Line 2,590 ⟶ 2,747:
for (var key in res) {
print(key + "\t" + res[key]);
}</langsyntaxhighlight>
Results in:
<pre>1,2,3 16619
Line 2,598 ⟶ 2,755:
3,1,2 16460
3,2,1 16596</pre>
 
 
===ES6===
 
====Mutating in-place swap====
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// knuthShuffle :: [a] -> [a]
Line 2,649 ⟶ 2,805:
return test();
})();
</syntaxhighlight>
</lang>
 
{{Out}}
e.g.
<langsyntaxhighlight JavaScriptlang="javascript">["iota", "epsilon", "kappa", "theta", "gamma", "delta",
"lambda", "eta", "zeta", "beta", "mu", "alpha"]</langsyntaxhighlight>
 
====Non-mutating swap====
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// knuthShuffle :: [a] -> [a]
Line 2,717 ⟶ 2,873:
// MAIN ---
return test();
})();</langsyntaxhighlight>
{{Out}}
e.g.
<langsyntaxhighlight JavaScriptlang="javascript">["mu", "theta", "beta", "eta", "delta", "epsilon",
"kappa", "alpha", "gamma", "lambda", "zeta", "iota"]</langsyntaxhighlight>
 
=={{header|Joy}}==
<langsyntaxhighlight Joylang="joy">DEFINE knuth-shuffle ==
 
(* Take the size of the array (without destroying it) *)
dup dup size
 
(* Generate a list of as many random numbers *)
[rand] [rem] enconcat map
 
(* Zip the two lists *)
swap zip
 
(* Sort according to the new index number *)
[small] [] [uncons unswonsd [first >] split [swons] dip2]
[enconcat] binrec
 
(* Delete the new index number *)
[second] map.</langsyntaxhighlight>
Using knuth-shuffle (file shuffle.joy):
<langsyntaxhighlight Joylang="joy">(* Sorted array of 21 integers *)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
knuth-shuffle.</langsyntaxhighlight>
Command line:
: <tt>joy shuffle.joy</tt>
Line 2,768 ⟶ 2,919:
 
where program.jq is the following program:
<syntaxhighlight lang="jq">
<lang jq>
# 52-card deck:
def deck:
Line 2,812 ⟶ 2,963:
task,
(deck|knuthShuffle | nwise(13) | implode)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,829 ⟶ 2,980:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function knuthshuffle!(r::AbstractRNG, v::AbstractVector)
for i in length(v):-1:2
j = rand(r, 1:i)
Line 2,839 ⟶ 2,990:
 
v = collect(1:20)
println("# v = $v\n -> ", knuthshuffle!(v))</langsyntaxhighlight>
 
{{out}}
Line 2,846 ⟶ 2,997:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">object Knuth {
internal val gen = java.util.Random()
}
Line 2,876 ⟶ 3,027:
require(s.toSortedSet() == ia.toSet())
}
}</langsyntaxhighlight>
{{out}}
<pre>xdhsvtnumjgbywiqoapcelkrfz
Line 2,905 ⟶ 3,056:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{def shuffle
 
Line 2,935 ⟶ 3,086:
{shuffle {B}}
-> [z,t,q,w,c,n,a,u,r,y,i,s,f,d,g,m,h,x,b,e,k,p,l,o,j,v]
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">define staticarray->swap(p1::integer,p2::integer) => {
fail_if(
#p1 < 1 or #p2 < 1 or
Line 2,957 ⟶ 3,108:
}
 
(1 to 10)->asStaticArray->knuthShuffle&asString</langsyntaxhighlight>
{{out}}
<pre>staticarray(9, 5, 6, 1, 10, 8, 3, 4, 2, 7)</pre>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">'Declared the UpperBound to prevent confusion with lots of 9's floating around....
UpperBound = 9
Dim array(UpperBound)
Line 2,983 ⟶ 3,134:
For i = 0 To UpperBound
Print array(i)
Next i</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to swap :i :j :a
localmake "t item :i :a
setitem :i :a item :j :a
Line 2,997 ⟶ 3,148:
make "a {1 2 3 4 5 6 7 8 9 10}
shuffle :a
show :a</langsyntaxhighlight>
Lhogho does not have a setitem, and also does things more 'function'ally.
<langsyntaxhighlight lang="logo">to slice :lst :start :finish
local "res
make "res []
Line 3,035 ⟶ 3,186:
make "a ( list 1 2 3 4 5 6 7 8 9 10 )
make "a shuffle :a
show :a</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function table.shuffle(t)
for n = #t, 1, -1 do
local k = math.random(n)
Line 3,050 ⟶ 3,201:
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
table.shuffle(a)
for i,v in ipairs(a) do print(i,v) end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Dim Base 0, A(3)
For k=1 to 6 {
Line 3,064 ⟶ 3,215:
}
 
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">divert(-1)
define(`randSeed',141592653)
define(`rand_t',`eval(randSeed^(randSeed>>13))')
Line 3,093 ⟶ 3,244:
show(`b')
shuffle(`b')
show(`b')</langsyntaxhighlight>
{{out}}
<pre>
Line 3,107 ⟶ 3,258:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Usage of built-in function:
<langsyntaxhighlight Mathematicalang="mathematica">RandomSample[{1, 2, 3, 4, 5, 6}]</langsyntaxhighlight>
Custom function:
<langsyntaxhighlight Mathematicalang="mathematica">Shuffle[input_List /; Length[input] >= 1] :=
Module[{indices = {}, allindices = Range[Length[input]]},
Do[
Line 3,118 ⟶ 3,269:
];
input[[indices]]
]</langsyntaxhighlight>
Example:
<langsyntaxhighlight Mathematicalang="mathematica">Shuffle[{1, 2, 3, 4, 5, 6}]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Because this shuffle is done using rounds of operations on subsets of decreasing size, this is not an algorithm that can be vectorized using built-in MATLAB functions. So, we have to go old-school, no fancy MATLAB trickery.
<langsyntaxhighlight MATLABlang="matlab">function list = knuthShuffle(list)
 
for i = (numel(list):-1:2)
Line 3,133 ⟶ 3,284:
list([j i]) = list([i j]);
end
end</langsyntaxhighlight>
There is an alternate way to do this that is not a true Knuth Shuffle, but operates with the same spirit.
This alternate version produces the same output, saves some space,
and can be implemented in-line without the need to encapsulate it
in a function call like the Knuth Shuffle.
<langsyntaxhighlight MATLABlang="matlab">function list = randSort(list)
list = list( randperm(numel(list)) );
end</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* Maxima has an implementation of Knuth shuffle */
random_permutation([a, b, c]);</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Shuffle EXPORTS Main;
 
IMPORT IO, Fmt, Random;
Line 3,177 ⟶ 3,328:
END;
IO.Put("\n");
END Shuffle.</langsyntaxhighlight>
{{out}}
<pre>
Line 3,187 ⟶ 3,338:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">Shuffle(items,separator) New ii,item,list,n
Set list="",n=0
Set ii="" For Set ii=$Order(items(ii)) Quit:ii="" Do
Line 3,270 ⟶ 3,421:
Queen of Spades
King of Diamonds
5 of Clubs</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">Shuffle[T] (arr : array[T]) : array[T]
{
def rnd = Random();
Line 3,280 ⟶ 3,431:
arr[i] <-> arr[(rnd.Next(i, arr.Length))];
arr
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
===version 1===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 3,332 ⟶ 3,483:
say
 
return</langsyntaxhighlight>
{{out}}
<pre>
Line 3,347 ⟶ 3,498:
 
===version 2===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx ------------------------------------------------------------
* 08.01.2014 Walter Pachl modified to show state development a la Rexx
*--------------------------------------------------------------------*/
Line 3,380 ⟶ 3,531:
method showHand(deck = ArrayList,tag=REXX) public static binary
say tag ArrayList(deck.subList(0,deck.size)).toString
return</langsyntaxhighlight>
{{out}}
<pre>In [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 3,396 ⟶ 3,547:
=={{header|Nim}}==
Note that the function "shuffle" exists in the standard module "random" and that it uses the Knuth shuffle.
<langsyntaxhighlight lang="nim">import random
randomize()
 
Line 3,406 ⟶ 3,557:
var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shuffle(x)
echo x</langsyntaxhighlight>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface NSMutableArray (KnuthShuffle)
Line 3,430 ⟶ 3,581:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,448 ⟶ 3,599:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let shuffle arr =
for n = Array.length arr - 1 downto 1 do
let k = Random.int (n + 1) in
Line 3,454 ⟶ 3,605:
arr.(n) <- arr.(k);
arr.(k) <- temp
done</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 3,461 ⟶ 3,612:
Returns a new list
 
<langsyntaxhighlight Oforthlang="oforth">Indexable method: shuffle
| s i l |
self asListBuffer ->l
self size dup ->s 1- loop: i [ s i - rand i + i l swapValues ]
l dup freeze ; </langsyntaxhighlight>
 
=={{header|Ol}}==
Line 3,472 ⟶ 3,623:
Ol is functional language, so we should make a copy of shuffling tuple and return this shuffled copy.
 
<langsyntaxhighlight lang="scheme">
(define (shuffle tp)
(let ((items (vm:cast tp (type tp)))) ; make a copy
Line 3,488 ⟶ 3,639:
(tuple->list
(shuffle (list->tuple (iota (length tp)))))))
</syntaxhighlight>
</lang>
 
Testing:
<langsyntaxhighlight lang="scheme">
(define items (tuple 1 2 3 4 5 6 7 8 9))
(print "tuple before: " items)
Line 3,499 ⟶ 3,650:
(print "list before: " items)
(print "list after: " (list-shuffle items))
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,509 ⟶ 3,660:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {Shuffle Arr}
Low = {Array.low Arr}
Line 3,527 ⟶ 3,678:
{Show {Array.toRecord unit X}}
{Shuffle X}
{Show {Array.toRecord unit X}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">FY(v)={
forstep(n=#v,2,-1,
my(i=random(n)+1,t=v[i]);
Line 3,539 ⟶ 3,690:
};
 
FY(vector(52,i,i))</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight Pascallang="pascal">program Knuth;
 
const
Line 3,593 ⟶ 3,744:
DisplayList(a);
end;
end.</langsyntaxhighlight>
{{out}}
<pre> -5 -4 -3 -2 -1 0 1 2 3 4 5
Line 3,604 ⟶ 3,755:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub shuffle {
my @a = @_;
foreach my $n (1 .. $#a) {
Line 3,611 ⟶ 3,762:
}
return @a;
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">cards</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">52</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Before: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">cards</span>
Line 3,623 ⟶ 3,774:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"After: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">cards</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Sorted: "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cards</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre style="font-size: 12px">
Line 3,632 ⟶ 3,783:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">//The Fisher-Yates original Method
function yates_shuffle($arr){
$shuffled = Array();
Line 3,649 ⟶ 3,800:
list($arr[$i], $arr[$rnd]) = array($arr[$rnd], $arr[$i]);
}
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
_ = random2(),
L = 1..10,
println(l_before=L),
knuth_shuffle(L),
println('l_after '=L),
nl.
 
knuth_shuffle(L) =>
foreach(I in L.len..-1..1)
J = random(1,I),
Tmp = L[I],
L[I] := L[J],
L[J] := Tmp
end.</syntaxhighlight>
 
{{out}}
<pre>l_before = [1,2,3,4,5,6,7,8,9,10]
l_after = [2,9,6,7,10,3,5,4,8,1]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(seed (in "/dev/urandom" (rd 8)))
 
(de knuth (Lst)
Line 3,662 ⟶ 3,834:
(println 'before L)
(knuth L)
(println 'after L) )</langsyntaxhighlight>
{{out}}
<pre>
Line 3,671 ⟶ 3,843:
=={{header|PL/I}}==
===version 1===
<langsyntaxhighlight lang="pli">declare T(0:10) fixed binary initial (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
declare (i, j, temp) fixed binary;
do i = lbound(T,1) to hbound(T,1);
j = min(random() * 12, 11);
temp = T(j); T(j) = T(i); T(i) = temp;
end;</langsyntaxhighlight>
 
===version 2===
<langsyntaxhighlight lang="pli"> kn: Proc Options(main);
/*--------------------------------------------------------------------
* 07.01.2014 Walter Pachl translated from REXX version 2
Line 3,701 ⟶ 3,873:
Put Edit(txt,(t(k) do k=1 To n))(Skip,a(7),10(f(3)));
End;
end;</langsyntaxhighlight>
{{out}}
<pre>In 1 2 3 4 5 6 7 8 9 10
Line 3,717 ⟶ 3,889:
=={{header|PowerShell}}==
{{works with|PowerShell|3}}
<langsyntaxhighlight lang="powershell">$A = 1, 2, 3, 4, 5
Get-Random $A -Count $A.Count</langsyntaxhighlight>
{{works with|PowerShell|2}} <!-- Get-Random didn't exist in PowerShell 1 -->
<langsyntaxhighlight lang="powershell">function shuffle ($a) {
$c = $a.Clone() # make copy to avoid clobbering $a
1..($c.Length - 1) | ForEach-Object {
Line 3,728 ⟶ 3,900:
}
$c[-1] # last value
}</langsyntaxhighlight>
This yields the values one by one instead of returning the array as a whole, so the rest of the pipeline can work on the values while shuffling is still in progress.
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
 
Procedure KnuthShuffle(Array a(1))
Line 3,763 ⟶ 3,935:
 
KnuthShuffle(a())
Debug "shuffled: " + ArrayToString(a())</langsyntaxhighlight>
{{out}}
<pre>shuffled: 1,8,6,0,5,9,2,4,7,3</pre>
Line 3,770 ⟶ 3,942:
Python's standard library function <code>[http://docs.python.org/library/random.html#random.shuffle random.shuffle]</code> uses this algorithm and so should normally be used.
The function below is very similar:
<langsyntaxhighlight lang="python">from random import randrange
 
def knuth_shuffle(x):
Line 3,779 ⟶ 3,951:
x = list(range(10))
knuth_shuffle(x)
print("shuffled:", x)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,788 ⟶ 3,960:
We could also write our own Knuth shuffle function as a fold, with a non-mutating swap function:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Knuth shuffle as a fold'''
 
from functools import reduce
Line 3,882 ⟶ 4,054:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Repeated Knuth shuffles of ['a' .. 'k']:
Line 3,902 ⟶ 4,074:
The word ''knuffle'' is ''probably'' an entirely in-place shuffle, ''if'' the dynamic memory allocation routines for a particular implementation of Quackery allow in-place modification of a dynamic array when there is only a single pointer to the array. (After the first invocation of ''poke'' inside ''[exch]'' there will definitely only be a single pointer to the array.)
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap dup size times
[ dup size random pluck
nested rot join swap ]
Line 3,922 ⟶ 4,094:
[ dup size 1 - times
[ i 1+ dup 1+ random
rot [exch] ] ] is knuffle ( [ --> [ )</langsyntaxhighlight>
 
{{out}}
Line 3,964 ⟶ 4,136:
===Original Fisher-Yates version===
<langsyntaxhighlight lang="rsplus">fisheryatesshuffle <- function(n)
{
pool <- seq_len(n)
Line 3,975 ⟶ 4,147:
}
a
}</langsyntaxhighlight>
===Knuth variation===
<langsyntaxhighlight lang="rsplus">fisheryatesknuthshuffle <- function(n)
{
a <- seq_len(n)
Line 3,997 ⟶ 4,169:
fisheryatesshuffle(6) # e.g. 1 3 6 2 4 5
x <- c("foo", "bar", "baz", "quux")
x[fisheryatesknuthshuffle(4)] # e.g. "bar" "baz" "quux" "foo"</langsyntaxhighlight>
===Short version===
After accounting for R being 1-indexed rather than 0-indexed, it's not hard to implement the pseudo-code given in the task almost exactly:
<langsyntaxhighlight lang="rsplus">knuth <- function(vec)
{
last <- length(vec)
Line 4,018 ⟶ 4,190:
replicate(10, knuth(c(10, 20)))
replicate(10, knuth(c(10, 20, 30)))
knuth(c("Also", "works", "for", "strings"))</langsyntaxhighlight>
{{Out}}
<pre>> knuth(integer(0))
Line 4,038 ⟶ 4,210:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="scheme">#lang racket
 
(define (swap! vec i j)
Line 4,053 ⟶ 4,225:
x)))
 
(knuth-shuffle '(1 2 3 4))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|#21 "Seattle"}}
<syntaxhighlight lang="raku" perl6line>sub shuffle (@a is copy) {
for 1 ..^ @a -> $n {
my $k = (0 .. $n).pick;
Line 4,064 ⟶ 4,236:
}
return @a;
}</langsyntaxhighlight>
The shuffle is also built into the pick method on lists when you pass it a "whatever" for the number to pick:
<syntaxhighlight lang="raku" perl6line>my @deck = @cards.pick(*);</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">REBOL [
Title: "Fisher-Yates"
Purpose: {Fisher-Yates shuffling algorithm}
Line 4,086 ⟶ 4,258:
]
b
]</langsyntaxhighlight>
 
=={{header|REXX}}==
===version 0, card pips===
<langsyntaxhighlight lang="rexx">/*REXX program shuffles a deck of playing cards (with jokers) using the Knuth shuffle.*/
rank= 'A 2 3 4 5 6 7 8 9 10 J Q K' /*pips of the various playing cards. */
suit= '♣♠♦♥' /*suit " " " " " */
Line 4,112 ⟶ 4,284:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: _=; do m=1 for cards; _=_ @.m; end /*m*/; say _; return</langsyntaxhighlight>
'''output'''
<pre>
Line 4,124 ⟶ 4,296:
===version 1, card names===
This version handles items with (leading/trailing/embedded) blanks in them, so &nbsp; '''parse''' &nbsp; isn't an option for shuffling.
<langsyntaxhighlight lang="rexx">/*REXX program shuffles a deck of playing cards (with jokers) using the Knuth shuffle.*/
rank = 'ace deuce trey 4 5 6 7 8 9 10 jack queen king' /*use pip names for cards*/
suit = 'club spade diamond heart' /* " suit " " " */
Line 4,150 ⟶ 4,322:
say 'card' right(m, 2) '───►' @.m /*display a particular card from deck. */
end /*m*/
return</langsyntaxhighlight>
'''output'''
<pre style="height:50ex">
Line 4,273 ⟶ 4,445:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 05.01.2014 Walter Pachl
* borrow one improvement from version 1
Line 4,295 ⟶ 4,467:
Do k=1 To n; ol=ol right(a.k,2); End
Say ol
Return</langsyntaxhighlight>
{{out}}
<pre>In 1 2 3 4 5 6 7 8 9 10
Line 4,310 ⟶ 4,482:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Knuth shuffle
 
Line 4,339 ⟶ 4,511:
see svect
see "]" + nl
</syntaxhighlight>
</lang>
<pre>
[15 1 51 20 45 29 43 8 13 3 41 35 11 7 37 9 38 17 32 48 40 25 44 18 14 50 42 34 2 21 12 4 26 19 23 24 28 46 36 10 5 16 6 49 22 33 39 47 31 52 30 27]
</pre>
 
=={{header|RPL}}==
Indexes of RPL lists and arrays start at 1.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
DUP SIZE 2 '''FOR''' j
j RAND * CEIL
GET LAST OVER j GET PUT j ROT PUT
-1 '''STEP'''
≫ '<span style="color:blue">KNUTH</span>' STO
|
<span style="color:blue">KNUTH</span> ''( {items} ➝ {items} )'' <span style="color:grey">// works also with [items]</span>
for j from last downto 2 do:
let k = random integer in range 1 ≤ k ≤ j
swap items[j] with items[k]
|}
 
=={{header|Ruby}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="ruby">class Array
def knuth_shuffle!
j = length
Line 4,366 ⟶ 4,561:
end
 
r.keys.sort.each {|a| puts "#{a.inspect} => #{r[a]}"}</langsyntaxhighlight>
results in
<pre>[1, 2, 3] => 16572
Line 4,375 ⟶ 4,570:
[3, 2, 1] => 16633</pre>
'''More idiomatic:'''
<langsyntaxhighlight lang="ruby">class Array
def knuth_shuffle!
(length - 1).downto(1) do |i|
Line 4,383 ⟶ 4,578:
self
end
end</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim cards(52)
for i = 1 to 52 ' make deck
cards(i) = i
Line 4,405 ⟶ 4,600:
if i mod 18 = 0 then print
next
print</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">use rand::Rng;
 
extern crate rand;
Line 4,429 ⟶ 4,624:
knuth_shuffle(&mut v);
println!("after: {:?}", v);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">def shuffle[T](a: Array[T]) = {
for (i <- 1 until a.size reverse) {
val j = util.Random nextInt (i + 1)
Line 4,440 ⟶ 4,635:
}
a
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
A functional version, using lists (inefficient), somewhat unusual in reversing the entire initial sublist on each pass instead of just swapping:
<langsyntaxhighlight Schemelang="scheme">#!r6rs
(import (rnrs base (6))
(srfi :27 random-bits))
Line 4,461 ⟶ 4,656:
(let
((li-prime (semireverse li (random-integer (length li)))))
(cons (car li-prime) (shuffle (cdr li-prime))))))</langsyntaxhighlight>
 
A mutable version, using vectors (efficient):
<langsyntaxhighlight Schemelang="scheme">#!r6rs
(import (rnrs base (6))
(srfi :27 random-bits))
Line 4,485 ⟶ 4,680:
((j (random-integer i)))
(vector-swap! vec (- i 1) j)))
(countdown (vector-length vec))))</langsyntaxhighlight>
 
=={{header|Scratch}}==
Line 4,491 ⟶ 4,686:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: intArray is array integer;
Line 4,522 ⟶ 4,717:
end for;
writeln;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,530 ⟶ 4,725:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">set list to 1..9 -- a range, will become a list as needed
set last to the number of items in list
 
Line 4,538 ⟶ 4,733:
end repeat
 
put list</langsyntaxhighlight>
{{out}}
<pre>
[8,9,7,3,4,5,1,2,6]
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program knuth_shuffle;
setrandom(0);
 
array := [1..10];
print("Before shuffling:", array);
shuffle(array);
print("After shuffling: ", array);
 
proc shuffle(rw tup);
loop for i in [1..#tup-1] do
j := random [i+1..#tup];
[tup(i), tup(j)] := [tup(j), tup(i)];
end loop;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>Before shuffling: [1 2 3 4 5 6 7 8 9 10]
After shuffling: [7 8 1 10 2 5 6 9 4 3]</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func knuth_shuffle(a) {
for i (a.len ^.. 1) {
var j = i.irand
Line 4,553 ⟶ 4,768:
}
 
say knuth_shuffle(@(1..10))</langsyntaxhighlight>
{{out}}
<pre>
Line 4,561 ⟶ 4,776:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">"The selector swap:with: is documented, but it seems not
implemented (GNU Smalltalk version 3.0.4); so here it is an implementation"
SequenceableCollection extend [
Line 4,582 ⟶ 4,797:
]
]
].</langsyntaxhighlight>
Testing
<langsyntaxhighlight lang="smalltalk">"Test"
|c|
c := OrderedCollection new.
c addAll: #( 1 2 3 4 5 6 7 8 9 ).
Shuffler Knuth: c.
c display.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4">* Library for random()
-include 'Random.sno'
 
Line 4,621 ⟶ 4,836:
shuffle(a)
output = a2s(a)
end</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 ->
2 10 4 9 1 5 6 8 7 3</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "shuffle" );
pragma annotate( description, "Implement the Knuth shuffle (aka the" );
pragma annotate( description, "Fisher-Yates-Durstenfeld shuffle)" );
pragma annotate( description, "for an integer array (or, if possible, an array of any" );
pragma annotate( description, "type). The Knuth shuffle is used to create a random" );
pragma annotate( description, "permutation of an array." );
pragma annotate( description, "Note: spar has a built-in arrays.shuffle() function that does this." );
pragma annotate( see_also, "http://rosettacode.org/wiki/Knuth_shuffle" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure shuffle is
 
subtype array_element_type is string;
type magic_items is array(1..3) of array_element_type;
 
a : magic_items := ( "bell", "book", "candle" );
t : array_element_type;
k : integer;
 
begin
 
for i in reverse arrays.first( a ) .. arrays.last( a )-1 loop
k := integer( numerics.rnd( i+1 ) ) - 1 + arrays.first(a);
t := a(i);
a(i) := a(k);
a(k) := t;
end loop;
 
for i in arrays.first( a ) .. arrays.last( a ) loop
? a(i);
end loop;
 
end shuffle;</syntaxhighlight>
{{out}}
<pre>
$ spar shuffle
bell
candle
book
 
$ spar shuffle
candle
bell
book</pre>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">mata
function shuffle(a) {
n = length(a)
Line 4,642 ⟶ 4,908:
 
shuffle(1..10)
end</langsyntaxhighlight>
 
'''Output'''
Line 4,652 ⟶ 4,918:
 
=={{header|Swift}}==
 
Version that works in Swift 5.x and probably above. This version works for any mutable bidirectional collection although O(n) time complexity can only be guaranteed for a RandomAccessCollection where the index meets the Apple requirements for O(1) access to elements.
 
Also has the advantage that it implemented the algorithm as written at the top of this page i.e. it counts down from the end and picks the random element from the part of the array that has not yet been traversed.
 
<syntaxhighlight lang="swift">extension BidirectionalCollection where Self: MutableCollection
{
mutating func shuffleInPlace()
{
var index = self.index(before: self.endIndex)
while index != self.startIndex
{
// Note the use of ... below. This makes the current element eligible for being selected
let randomInt = Int.random(in: 0 ... self.distance(from: startIndex, to: index))
let randomIndex = self.index(startIndex, offsetBy: randomInt)
self.swapAt(index, randomIndex)
index = self.index(before: index)
}
}
}
 
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.shuffleInPlace()
print(a)
</syntaxhighlight>
{{out}}
<pre>[1, 5, 2, 7, 6, 0, 9, 8, 4, 3]</pre>
 
'''Simple version (any Swift version):''' Extend Array with shuffle methods; using arc4random_uniform from C stdlib:
 
<langsyntaxhighlight lang="swift">import func Darwin.arc4random_uniform
 
extension Array {
Line 4,674 ⟶ 4,967:
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())
// Swift 1.x:
//println([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())</langsyntaxhighlight>
 
{{out}}
Line 4,681 ⟶ 4,974:
'''Generic version (any Swift version):''' While the above code is generic in that it works with arrays of any element type, we can use generic global functions to define shuffling for any mutable collection with random-access index type which is far more generic than the above code:
 
<langsyntaxhighlight lang="swift">import func Darwin.arc4random_uniform
 
func shuffleInPlace<T: MutableCollectionType where T.Index: RandomAccessIndexType>(inout collection: T) {
Line 4,711 ⟶ 5,004:
print(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
// Swift 1.x:
//println(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))</langsyntaxhighlight>
 
{{out}}
Line 4,718 ⟶ 5,011:
{{works with|Swift | 2.0 }} While the above solutions work with Swift 2.0 as they are, we can use Swift 2.0's Protocol Oriented Programming features to add shuffling methods to any mutable collection that has a random-access index:
 
<langsyntaxhighlight lang="swift">import func Darwin.arc4random_uniform
 
// Define a protocol for shuffling:
Line 4,767 ⟶ 5,060:
{ /* Implementation provided by Shufflable protocol extension */ }
 
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())</langsyntaxhighlight>
 
{{out}}
Line 4,773 ⟶ 5,066:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc knuth_shuffle lst {
set j [llength $lst]
for {set i 0} {$j > 1} {incr i;incr j -1} {
Line 4,789 ⟶ 5,082:
5 2 1 4 3
% knuth_shuffle {tom dick harry peter paul mary}
tom paul mary harry peter dick</langsyntaxhighlight>
As a test of skewing (an indicator of a poor implementation) this code was used:
<langsyntaxhighlight lang="tcl">% for {set i 0} {$i<100000} {incr i} {
foreach val [knuth_shuffle {1 2 3 4 5}] pos {pos0 pos1 pos2 pos3 pos4} {
incr tots($pos) $val
Line 4,801 ⟶ 5,094:
tots(pos2) = 299701
tots(pos3) = 299830
tots(pos4) = 300240</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 4,820 ⟶ 5,113:
:DelVar D
:Return
 
=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd
 
MainModule: {
// Define an abstract type Vec to make the shuffling
// function polymorphic
Vec: typedef(Lambda<:Data Bool>(λ d :Data()
(starts-with (_META_type d) "Vector<"))),
 
kshuffle: (λ v Vec() locals: rnd 0
(for n in Range( (- (size v) 1) 0) do
(= rnd (randr (to-Int n)))
(with tmp (cp (get v n))
(set-el v n (get v rnd))
(set-el v rnd tmp))
)
(lout v)
),
_start: (λ
(with v [10,20,30,40,50,60,70,80,90,100]
(lout "Original:\n" v)
(lout "Shuffled:")
(kshuffle v))
(lout "")
(with v ["A","B","C","D","E","F","G","H"]
(lout "Original:\n" v)
(lout "Shuffled:")
(kshuffle (cp v))
// Transd has a built-in function that performs the same
// kind of random shuffle
(lout "Built-in shuffle:")
(lout (shuffle v)))
)
}</syntaxhighlight>
{{out}}
<pre>
Original:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Shuffled:
[20, 60, 100, 80, 70, 10, 50, 90, 40, 30]
 
Original:
["A", "B", "C", "D", "E", "F", "G", "H"]
Shuffled:
["G", "A", "D", "B", "F", "E", "C", "H"]
Built-in shuffle:
["A", "E", "C", "H", "G", "F", "B", "D"]
</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
oldnumbers=newnumbers="",range=20
LOOP nr=1,#range
Line 4,836 ⟶ 5,178:
ENDLOOP
 
PRINT "after ",newnumbers</langsyntaxhighlight>
{{out}}
<pre>
Line 4,844 ⟶ 5,186:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "before:"
FOR L = 0 TO 51
@(L) = L
Line 4,865 ⟶ 5,207:
END
 
100 @(POP()) = POP() : @(POP()) = POP() : RETURN</langsyntaxhighlight>
{{out}}
<pre>before:
Line 4,871 ⟶ 5,213:
after:
19 4 49 9 27 35 50 11 2 29 22 48 33 15 17 42 47 28 41 18 34 21 30 39 3 8 23 12 36 26 0 46 7 44 13 14 16 40 10 25 31 32 51 24 20 38 45 6 43 1 5 37</pre>
 
=={{header|Uiua}}==
{{works with|Uiua|0.10.0-dev.1}}
Build pairs of indexes to be swapped then apply these as a fold.
<syntaxhighlight lang="Uiua">
Knuth ← ∧(⍜⊏⇌)≡(⊟⌊×⚂.)⇌↘1⇡⧻.
Knuth ⇡10
</syntaxhighlight>
Typical output:
<pre>
[3 0 6 5 7 8 4 1 9 2]
</pre>
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
{{works with|pdksh}}
<langsyntaxhighlight lang="bash"># Shuffle array[@].
function shuffle {
integer i j t
Line 4,895 ⟶ 5,249:
set -A array 11 22 33 44 55 66 77 88 99 110
shuffle
echo "${array[@]}"</langsyntaxhighlight>
 
=={{header|Ursala}}==
This function works on lists of any type and length, including character strings.
<langsyntaxhighlight Ursalalang="ursala">shuffle = @iNX ~&l->r ^jrX/~&l ~&lK8PrC</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %s
 
example = shuffle 'abcdefghijkl'</langsyntaxhighlight>
{{out}}
<pre>'keacfjlbdigh'</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Sub Knuth(Optional ByRef a As Variant)
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
Line 4,956 ⟶ 5,310:
Debug.Print "After: ";
For Each i In f: Debug.Print i;: Next i: Debug.Print
End Sub</langsyntaxhighlight>{{out}}<pre>Before:
After:
Before: 10
Line 4,972 ⟶ 5,326:
=={{header|VBScript}}==
;Implementation
<syntaxhighlight lang="vb">
<lang vb>
function shuffle( a )
dim i
Line 4,991 ⟶ 5,345:
a = b
b = tmp
end sub</langsyntaxhighlight>
;Invocation
<langsyntaxhighlight lang="vb">dim a
a = array( 1,2,3,4,5,6,7,8,9)
wscript.echo "before: ", join( a, ", " )
Line 5,006 ⟶ 5,360:
wscript.echo "after: ", join( a, ", " )
shuffle a
wscript.echo "after: ", join( a, ", " )</langsyntaxhighlight>
{{out}}
<pre>
Line 5,023 ⟶ 5,377:
 
The output will be inserted in current edit buffer.
<langsyntaxhighlight lang="vedit">// Test main
#90 = Time_Tick // seed for random number generator
#99 = 20 // number of items in the array
Line 5,064 ⟶ 5,418:
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)</langsyntaxhighlight>
{{out}}
<pre>Before:
Line 5,071 ⟶ 5,425:
9 13 8 18 10 1 17 15 0 16 14 19 3 2 7 11 6 4 5 12 </pre>
 
=={{header|V (Vlang)}}==
Updated to Vlang version 0.2.2
<langsyntaxhighlight lang="go">import rand
import rand.seed
 
Line 5,093 ⟶ 5,447:
println('Output: $arr')
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Input: [6, 9, 1, 4]
Line 5,101 ⟶ 5,455:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
 
var rand = Random.new()
Line 5,121 ⟶ 5,475:
knuthShuffle.call(a)
System.print("%(b) -> %(a)")
}</langsyntaxhighlight>
 
{{out}}
Line 5,133 ⟶ 5,487:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">proc Shuffle(Array, Items, BytesPerItem);
int Array, Items, BytesPerItem;
int I, J;
Line 5,168 ⟶ 5,522:
[IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 5,177 ⟶ 5,531:
10
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: https://www.rosettacode.org/wiki/Ramsey%27s_theorem
// by Jjuanhdez, 06/2022
 
dim array(52)
for i = 1 to arraysize(array(),1) : array(i) = i : next i
 
print "Starting array"
for i = 1 to arraysize(array(),1)
print array(i) using "####";
next i
 
KnuthShuffle(array())
 
print "\n\nAfter Knuth shuffle downwards"
for i = 1 to arraysize(array(),1)
print array(i) using "####";
next i
print
end
 
sub KnuthShuffle(a())
local i, j, t, lb, ub
lb = 1
ub = arraysize(a(),1) - lb
for i = lb to ub
j = round(ran(i +1))
t = a(lb + i)
a(lb + i) = a(lb + j)
a(lb + j) = t
next i
end sub</syntaxhighlight>
 
=={{header|zkl}}==
Two versions, imperative and functional, same results.
xs has to be a mutable list.
<langsyntaxhighlight lang="zkl">fcn kshuffle(xs){
foreach i in ([xs.len()-1..1,-1]){ xs.swap(i,(0).random(0,i+1)) }
xs
Line 5,188 ⟶ 5,576:
[xs.len()-1..1,-1].pump(Void,'wrap(i){ xs.swap(i,(0).random(0,i+1)) })
xs
}</langsyntaxhighlight>
<pre>
var ns=(1).pump(10,List).copy() // [1..10] made mutable
60

edits