Knuth shuffle: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 53: Line 53:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F knuth_shuffle(&x)
<syntaxhighlight lang="11l">F knuth_shuffle(&x)
L(i) (x.len - 1 .< 0).step(-1)
L(i) (x.len - 1 .< 0).step(-1)
V j = random:(0..i)
V j = random:(0..i)
Line 60: Line 60:
V x = Array(0..9)
V x = Array(0..9)
knuth_shuffle(&x)
knuth_shuffle(&x)
print(‘shuffled: ’x)</lang>
print(‘shuffled: ’x)</syntaxhighlight>


{{out}}
{{out}}
Line 69: Line 69:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<lang 360asm>
<syntaxhighlight lang="360asm">
* Knuth shuffle 02/11/2015
* Knuth shuffle 02/11/2015
KNUTHSH CSECT
KNUTHSH CSECT
Line 119: Line 119:
YREGS
YREGS
END KNUTHSH
END KNUTHSH
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 129: 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.
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.


<lang 6502asm>define sysRandom $fe
<syntaxhighlight lang="6502asm">define sysRandom $fe
define tempMask $ff
define tempMask $ff
define range $00
define range $00
Line 197: Line 197:


end:
end:
brk</lang>
brk</syntaxhighlight>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program knuthshuffle64.s */
/* program knuthshuffle64.s */
Line 343: Line 343:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>:set-state-ok t
<syntaxhighlight lang="lisp">:set-state-ok t


(defun array-swap (name array i j)
(defun array-swap (name array i j)
Line 369: Line 369:
array
array
(1- (first (dimensions name array)))
(1- (first (dimensions name array)))
state))</lang>
state))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC PrintTable(INT ARRAY tab BYTE size)
<syntaxhighlight lang="action!">PROC PrintTable(INT ARRAY tab BYTE size)
BYTE i
BYTE i


Line 414: Line 414:
PrintE("Shuffled data:")
PrintE("Shuffled data:")
PrintTable(tab,size)
PrintTable(tab,size)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Knuth_shuffle.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Knuth_shuffle.png Screenshot from Atari 8-bit computer]
Line 427: Line 427:
=={{header|Ada}}==
=={{header|Ada}}==
This implementation is a generic shuffle routine, able to shuffle an array of any type.
This implementation is a generic shuffle routine, able to shuffle an array of any type.
<lang Ada>generic
<syntaxhighlight lang="ada">generic
type Element_Type is private;
type Element_Type is private;
type Array_Type is array (Positive range <>) of Element_Type;
type Array_Type is array (Positive range <>) of Element_Type;
procedure Generic_Shuffle (List : in out Array_Type);</lang>
procedure Generic_Shuffle (List : in out Array_Type);</syntaxhighlight>
<lang Ada>with Ada.Numerics.Discrete_Random;
<syntaxhighlight lang="ada">with Ada.Numerics.Discrete_Random;


procedure Generic_Shuffle (List : in out Array_Type) is
procedure Generic_Shuffle (List : in out Array_Type) is
Line 448: Line 448:
List(K) := T;
List(K) := T;
end loop;
end loop;
end Generic_Shuffle;</lang>
end Generic_Shuffle;</syntaxhighlight>
An example using Generic_Shuffle.
An example using Generic_Shuffle.
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Generic_Shuffle;
with Generic_Shuffle;


Line 471: Line 471:
Ada.Text_IO.Put(Integer'Image(Integer_List(I)));
Ada.Text_IO.Put(Integer'Image(Integer_List(I)));
end loop;
end loop;
end Test_Shuffle;</lang>
end Test_Shuffle;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
The shuffle function works on any type (the lists are heterogenous).
The shuffle function works on any type (the lists are heterogenous).
<lang aime>void
<syntaxhighlight lang="aime">void
shuffle(list l)
shuffle(list l)
{
{
Line 488: Line 488:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G}}
{{works with|ALGOL 68G}}
<lang algol68>PROC between = (INT a, b)INT :
<syntaxhighlight lang="algol68">PROC between = (INT a, b)INT :
(
(
ENTIER (random * ABS (b-a+1) + (a<b|a|b))
ENTIER (random * ABS (b-a+1) + (a<b|a|b))
Line 505: Line 505:
a[j] := t
a[j] := t
OD
OD
);</lang>
);</syntaxhighlight>
<lang algol68>main:(
<syntaxhighlight lang="algol68">main:(
[20]INT a;
[20]INT a;
FOR i FROM 1 TO 20 DO a[i] := i OD;
FOR i FROM 1 TO 20 DO a[i] := i OD;
knuth shuffle(a);
knuth shuffle(a);
print(a)
print(a)
)</lang>
)</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 517: Line 517:
===Iteration===
===Iteration===


<lang AppleScript>set n to 25
<syntaxhighlight lang="applescript">set n to 25


set array to {}
set array to {}
Line 530: Line 530:
end repeat
end repeat


return {unshuffled, shuffled}</lang>
return {unshuffled, shuffled}</syntaxhighlight>
Example:
Example:
<lang 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},
<syntaxhighlight lang="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}}</lang>
{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}}</syntaxhighlight>


----
----
Better:
Better:
<lang applescript>-- Fisher-Yates (aka Durstenfeld, aka Knuth) shuffle.
<syntaxhighlight lang="applescript">-- Fisher-Yates (aka Durstenfeld, aka Knuth) shuffle.
on shuffle(theList, l, r)
on shuffle(theList, l, r)
set listLength to (count theList)
set listLength to (count theList)
Line 561: Line 561:
set array to {"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike"}
set array to {"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike"}
-- Shuffle all items (1 thru -1).
-- Shuffle all items (1 thru -1).
shuffle(array, 1, -1)</lang>
shuffle(array, 1, -1)</syntaxhighlight>


{{output}}
{{output}}
''eg.''
''eg.''
<lang applescript>{"Golf", "Foxtrot", "Echo", "Delta", "Kilo", "Charlie", "Mike", "Alpha", "Lima", "Juliett", "India", "Bravo", "Hotel"}</lang>
<syntaxhighlight lang="applescript">{"Golf", "Foxtrot", "Echo", "Delta", "Kilo", "Charlie", "Mike", "Alpha", "Lima", "Juliett", "India", "Bravo", "Hotel"}</syntaxhighlight>


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:
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:
<lang applescript>use AppleScript version "2.5" -- OS X 10.11 (El Capitan) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.5" -- OS X 10.11 (El Capitan) or later
use framework "Foundation"
use framework "Foundation"
use framework "GameplayKit"
use framework "GameplayKit"
Line 591: Line 591:
return theList
return theList
end shuffle</lang>
end shuffle</syntaxhighlight>
----
----


===Functional composition===
===Functional composition===


<lang AppleScript>-- KNUTH SHUFFLE -------------------------------------------------------------
<syntaxhighlight lang="applescript">-- KNUTH SHUFFLE -------------------------------------------------------------


-- knuthShuffle :: [a] -> [a]
-- knuthShuffle :: [a] -> [a]
Line 667: Line 667:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
e.g.
e.g.
<lang AppleScript>{"mu", "theta", "alpha", "delta", "zeta", "gamma",
<syntaxhighlight lang="applescript">{"mu", "theta", "alpha", "delta", "zeta", "gamma",
"iota", "kappa", "lambda", "epsilon", "beta", "eta"}</lang>
"iota", "kappa", "lambda", "epsilon", "beta", "eta"}</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 908: Line 908:




</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>knuth: function [arr][
<syntaxhighlight lang="rebol">knuth: function [arr][
if 0=size arr -> return []
if 0=size arr -> return []
Line 928: Line 928:
print knuth [10]
print knuth [10]
print knuth [10 20]
print knuth [10 20]
print knuth [10 20 30]</lang>
print knuth [10 20 30]</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=133 discussion]
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=133 discussion]
<lang AutoHotkey>MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
<syntaxhighlight lang="autohotkey">MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
MsgBox % shuffle("1,2,3,4,5,6,7,8,9")


Line 944: Line 944:
s .= "," . a%A_Index%
s .= "," . a%A_Index%
Return SubStr(s,2) ; drop leading comma
Return SubStr(s,2) ; drop leading comma
}</lang>
}</syntaxhighlight>


For Arrays:
For Arrays:
Line 951: Line 951:


[https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array#6274381 (translated from)]
[https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array#6274381 (translated from)]
<lang AutoHotkey>toShuffle:=[1,2,3,4,5,6]
<syntaxhighlight lang="autohotkey">toShuffle:=[1,2,3,4,5,6]
shuffled:=shuffle(toShuffle)
shuffled:=shuffle(toShuffle)
;p(toShuffle) ;because it modifies the original array
;p(toShuffle) ;because it modifies the original array
Line 967: Line 967:
}
}
return a
return a
}</lang>
}</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
Dim $a[10]
Dim $a[10]
ConsoleWrite('array before permutation:' & @CRLF)
ConsoleWrite('array before permutation:' & @CRLF)
Line 996: Line 996:
Next
Next
EndFunc
EndFunc
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,010: Line 1,010:
This example shows how to shuffle such arrays.
This example shows how to shuffle such arrays.
The elements can be integers, floating-point numbers, or strings.
The elements can be integers, floating-point numbers, or strings.
<lang awk># Shuffle an _array_ with indexes from 1 to _len_.
<syntaxhighlight lang="awk"># Shuffle an _array_ with indexes from 1 to _len_.
function shuffle(array, len, i, j, t) {
function shuffle(array, len, i, j, t) {
for (i = len; i > 1; i--) {
for (i = len; i > 1; i--) {
Line 1,030: Line 1,030:
for (i = 1; i < len; i++) printf "%s ", array[i]
for (i = 1; i < len; i++) printf "%s ", array[i]
printf "%s\n", array[len]
printf "%s\n", array[len]
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang qbasic>RANDOMIZE TIMER
<syntaxhighlight lang="qbasic">RANDOMIZE TIMER


DIM cards(51) AS INTEGER
DIM cards(51) AS INTEGER
Line 1,053: Line 1,053:
PRINT LTRIM$(STR$(cards(L0))); " ";
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT
NEXT
PRINT</lang>
PRINT</syntaxhighlight>


{{out}}
{{out}}
Line 1,067: Line 1,067:
==={{header|Applesoft BASIC}}===
==={{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.
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.
<lang basic> 100 :
<syntaxhighlight lang="basic"> 100 :
110 REM KNUTH SHUFFLE
110 REM KNUTH SHUFFLE
120 :
120 :
Line 1,080: Line 1,080:
210 PRINT A(I);" ";: NEXT I
210 PRINT A(I);" ";: NEXT I
220 END
220 END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1
<pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1
Line 1,089: Line 1,089:


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> cards% = 52
<syntaxhighlight lang="bbcbasic"> cards% = 52
DIM pack%(cards%)
DIM pack%(cards%)
FOR I% = 1 TO cards%
FOR I% = 1 TO cards%
Line 1,100: Line 1,100:
PRINT pack%(I%);
PRINT pack%(I%);
NEXT I%
NEXT I%
PRINT</lang>
PRINT</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Shuffle.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "Shuffle.bas"
110 RANDOMIZE
110 RANDOMIZE
120 NUMERIC ARRAY(1 TO 20)
120 NUMERIC ARRAY(1 TO 20)
Line 1,126: Line 1,126:
310 IF CARD<>I THEN LET T=A(CARD):LET A(CARD)=A(I):LET A(I)=T
310 IF CARD<>I THEN LET T=A(CARD):LET A(CARD)=A(I):LET A(I)=T
320 NEXT
320 NEXT
330 END DEF</lang>
330 END DEF</syntaxhighlight>


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
<lang>
<syntaxhighlight lang="text">
uses chaos
uses chaos
uses timeutil
uses timeutil
Line 1,140: Line 1,140:
swap d[i],d[j]
swap d[i],d[j]
next
next
</syntaxhighlight>
</lang>


==={{header|QB64}}===
==={{header|QB64}}===
Shuffle and make sure that number does not take its place<br/>
Shuffle and make sure that number does not take its place<br/>
and between cells at least 10% ... Shuffle from Russia
and between cells at least 10% ... Shuffle from Russia
<lang qbasic>
<syntaxhighlight lang="qbasic">
a = 100: DIM d(a): x=0: k=0: t$=CHR$(9): RANDOMIZE TIMER 'Shuffle_RUS.bas
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
PRINT ,: FOR i = 1 TO a: d(i)=i: NEXT
Line 1,169: Line 1,169:
IF d(i) = i THEN PRINT -d(i); ELSE PRINT d(i);
IF d(i) = i THEN PRINT -d(i); ELSE PRINT d(i);
NEXT
NEXT
WEND: PRINT: PRINT " = "; k, TIMER-z: END</lang>
WEND: PRINT: PRINT " = "; k, TIMER-z: END</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Line 1,175: Line 1,175:


The program works with the unexpanded (1k RAM) ZX81.
The program works with the unexpanded (1k RAM) ZX81.
<lang basic> 10 RAND
<syntaxhighlight lang="basic"> 10 RAND
20 LET A$=""
20 LET A$=""
30 FOR I=1 TO 26
30 FOR I=1 TO 26
Line 1,188: Line 1,188:
120 PRINT AT 0,I-1;CHR$ (CODE A$(I)+128)
120 PRINT AT 0,I-1;CHR$ (CODE A$(I)+128)
130 PRINT AT 0,J-1;CHR$ (CODE A$(J)+128)
130 PRINT AT 0,J-1;CHR$ (CODE A$(J)+128)
140 NEXT I</lang>
140 NEXT I</syntaxhighlight>
{{out}}
{{out}}
While the program is running, we will see something like this (using lower case as a stand-in for inverse video):
While the program is running, we will see something like this (using lower case as a stand-in for inverse video):
Line 1,197: Line 1,197:
==={{header|True BASIC}}===
==={{header|True BASIC}}===
{{trans|BASIC}}
{{trans|BASIC}}
<lang qbasic>OPTION BASE 0
<syntaxhighlight lang="qbasic">OPTION BASE 0
RANDOMIZE
RANDOMIZE


Line 1,222: Line 1,222:
PRINT LTRIM$(STR$(cards(L0))); " ";
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT L0
NEXT L0
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>Same as BASIC entry.</pre>
<pre>Same as BASIC entry.</pre>
Line 1,231: Line 1,231:
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.
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}}
{{works with|OpenBSD bc}}
<lang bc>seed = 1 /* seed of the random number generator */
<syntaxhighlight lang="bc">seed = 1 /* seed of the random number generator */
scale = 0
scale = 0


Line 1,274: Line 1,274:
trash = shuffle(10)
trash = shuffle(10)
"Shuffled array: "; trash = print_array(10)
"Shuffled array: "; trash = print_array(10)
quit</lang>
quit</syntaxhighlight>
{{out}}
{{out}}
<pre>Original array: 11, 22, 33, 44, 55, 66, 77, 88, 99, 110
<pre>Original array: 11, 22, 33, 44, 55, 66, 77, 88, 99, 110
Line 1,283: Line 1,283:
BQN's arrays are immutable, but variable values can be changed using the `↩` symbol. This program repeatedly changes the array's value using under.
BQN's arrays are immutable, but variable values can be changed using the `↩` symbol. This program repeatedly changes the array's value using under.


<lang bqn>Knuth ← {
<syntaxhighlight lang="bqn">Knuth ← {
𝕊 arr:
𝕊 arr:
l ← ≠arr
l ← ≠arr
Line 1,296: Line 1,296:
P ⟨10⟩
P ⟨10⟩
P ⟨10, 20⟩
P ⟨10, 20⟩
P ⟨10, 20, 30⟩</lang>
P ⟨10, 20, 30⟩</syntaxhighlight>


[https://mlochbaum.github.io/BQN/try.html#code=S251dGgg4oaQIHsKICDwnZWKIGFycjoKICBsIOKGkCDiiaBhcnIKICB7CiAgICBhcnIg4oapIOKMveKMvijin6jigKJyYW5kLlJhbmdlIGwsIPCdlanin6niirjiio8pYXJyCiAgfcKo4oaVbAogIGFycgp9ClAg4oaQIOKAolNob3cgS251dGgKClAg4p+o4p+pClAg4p+oMTDin6kKUCDin6gxMCwgMjDin6kKUCDin6gxMCwgMjAsIDMw4p+p Try It!]
[https://mlochbaum.github.io/BQN/try.html#code=S251dGgg4oaQIHsKICDwnZWKIGFycjoKICBsIOKGkCDiiaBhcnIKICB7CiAgICBhcnIg4oapIOKMveKMvijin6jigKJyYW5kLlJhbmdlIGwsIPCdlanin6niirjiio8pYXJyCiAgfcKo4oaVbAogIGFycgp9ClAg4oaQIOKAolNob3cgS251dGgKClAg4p+o4p+pClAg4p+oMTDin6kKUCDin6gxMCwgMjDin6kKUCDin6gxMCwgMjAsIDMw4p+p Try It!]


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>shuffle = { a |
<syntaxhighlight lang="brat">shuffle = { a |
(a.length - 1).to 1 { i |
(a.length - 1).to 1 { i |
random_index = random(0, i)
random_index = random(0, i)
Line 1,312: Line 1,312:
}
}


p shuffle [1 2 3 4 5 6 7]</lang>
p shuffle [1 2 3 4 5 6 7]</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
This shuffles any "object"; it imitates <tt>qsort</tt> in the syntax.
This shuffles any "object"; it imitates <tt>qsort</tt> in the syntax.
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
#include <string.h>


Line 1,336: Line 1,336:
}
}
free(temp);
free(temp);
} </lang>
} </syntaxhighlight>
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:
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:
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 1,389: Line 1,389:
printf(" %d", x[i]);
printf(" %d", x[i]);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>public static void KnuthShuffle<T>(T[] array)
<syntaxhighlight lang="csharp">public static void KnuthShuffle<T>(T[] array)
{
{
System.Random random = new System.Random();
System.Random random = new System.Random();
Line 1,400: Line 1,400:
T temp = array[i]; array[i] = array[j]; array[j] = temp;
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
'''Compiler:''' [[g++]] (version 4.3.2 20081105 (Red Hat 4.3.2-7))
'''Compiler:''' [[g++]] (version 4.3.2 20081105 (Red Hat 4.3.2-7))
<lang cpp>#include <cstdlib>
<syntaxhighlight lang="cpp">#include <cstdlib>
#include <algorithm>
#include <algorithm>
#include <iterator>
#include <iterator>
Line 1,416: Line 1,416:
}
}
}
}
}</lang>
}</syntaxhighlight>
The standard library provides this in the form of <code>std::random_shuffle</code>.
The standard library provides this in the form of <code>std::random_shuffle</code>.
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <vector>
#include <vector>


Line 1,428: Line 1,428:
std::random_shuffle(array, array + 9); // shuffle C-style array
std::random_shuffle(array, array + 9); // shuffle C-style array
std::random_shuffle(vec.begin(), vec.end()); // shuffle STL container
std::random_shuffle(vec.begin(), vec.end()); // shuffle STL container
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(defn shuffle [vect]
<syntaxhighlight lang="lisp">(defn shuffle [vect]
(reduce (fn [v i] (let [r (rand-int i)]
(reduce (fn [v i] (let [r (rand-int i)]
(assoc v i (v r) r (v i))))
(assoc v i (v r) r (v i))))
vect (range (dec (count vect)) 1 -1)))</lang>
vect (range (dec (count vect)) 1 -1)))</syntaxhighlight>
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.
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}}==
=={{header|CLU}}==
<lang clu>knuth_shuffle = proc [T: type] (a: array[T])
<syntaxhighlight lang="clu">knuth_shuffle = proc [T: type] (a: array[T])
lo: int := array[T]$low(a)
lo: int := array[T]$low(a)
hi: int := array[T]$high(a)
hi: int := array[T]$high(a)
Line 1,458: Line 1,458:
stream$puts(po, int$unparse(i) || " ")
stream$puts(po, int$unparse(i) || " ")
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>7 9 2 3 4 8 1 6 5</pre>
<pre>7 9 2 3 4 8 1 6 5</pre>
Line 1,464: Line 1,464:


=={{header|CMake}}==
=={{header|CMake}}==
<lang cmake># shuffle(<output variable> [<value>...]) shuffles the values, and
<syntaxhighlight lang="cmake"># shuffle(<output variable> [<value>...]) shuffles the values, and
# stores the result in a list.
# stores the result in a list.
function(shuffle var)
function(shuffle var)
Line 1,496: Line 1,496:
endforeach(i)
endforeach(i)
set("${var}" ${answer} PARENT_SCOPE)
set("${var}" ${answer} PARENT_SCOPE)
endfunction(shuffle)</lang>
endfunction(shuffle)</syntaxhighlight>


<lang cmake>shuffle(result 11 22 33 44 55 66)
<syntaxhighlight lang="cmake">shuffle(result 11 22 33 44 55 66)
message(STATUS "${result}")
message(STATUS "${result}")
# One possible output:
# One possible output:
# -- 66;33;22;55;44;11</lang>
# -- 66;33;22;55;44;11</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. knuth-shuffle.
PROGRAM-ID. knuth-shuffle.


Line 1,532: Line 1,532:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang coffeescript>knuth_shuffle = (a) ->
<syntaxhighlight lang="coffeescript">knuth_shuffle = (a) ->
n = a.length
n = a.length
while n > 1
while n > 1
Line 1,556: Line 1,556:


for key, val of counts
for key, val of counts
console.log "#{key}: #{val}"</lang>
console.log "#{key}: #{val}"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,569: Line 1,569:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun nshuffle (sequence)
<syntaxhighlight lang="lisp">(defun nshuffle (sequence)
(loop for i from (length sequence) downto 2
(loop for i from (length sequence) downto 2
do (rotatef (elt sequence (random i))
do (rotatef (elt sequence (random i))
(elt sequence (1- i))))
(elt sequence (1- i))))
sequence)</lang>
sequence)</syntaxhighlight>
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>):
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>):
<lang lisp>(defun nshuffle (sequence)
<syntaxhighlight lang="lisp">(defun nshuffle (sequence)
(etypecase sequence
(etypecase sequence
(list (nshuffle-list sequence))
(list (nshuffle-list sequence))
Line 1,590: Line 1,590:
do (rotatef (aref array (random i))
do (rotatef (aref array (random i))
(aref array (1- i)))
(aref array (1- i)))
finally (return array)))</lang>
finally (return array)))</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang crystal>def knuthShuffle(items : Array)
<syntaxhighlight lang="crystal">def knuthShuffle(items : Array)
i = items.size-1
i = items.size-1
while i > 1
while i > 1
Line 1,601: Line 1,601:
i -= 1
i -= 1
end
end
end</lang>
end</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===Standard Version===
===Standard Version===
A variant of the Knuth shuffle is in the D standard library Phobos:
A variant of the Knuth shuffle is in the D standard library Phobos:
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.random;
import std.stdio, std.random;


Line 1,612: Line 1,612:
a.randomShuffle;
a.randomShuffle;
a.writeln;
a.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[8, 9, 3, 1, 7, 5, 4, 6, 2]</pre>
<pre>[8, 9, 3, 1, 7, 5, 4, 6, 2]</pre>
Line 1,618: Line 1,618:
===One Implementation===
===One Implementation===
This shuffles any collection that supports random access, length and swapping of items:
This shuffles any collection that supports random access, length and swapping of items:
<lang d>import std.stdio, std.algorithm, std.random, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.random, std.range;


void knuthShuffle(Range)(Range r)
void knuthShuffle(Range)(Range r)
Line 1,631: Line 1,631:
a.knuthShuffle;
a.knuthShuffle;
a.writeln;
a.writeln;
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 1,637: Line 1,637:


=={{header|DWScript}}==
=={{header|DWScript}}==
<lang delphi>procedure KnuthShuffle(a : array of Integer);
<syntaxhighlight lang="delphi">procedure KnuthShuffle(a : array of Integer);
var
var
i, j, tmp : Integer;
i, j, tmp : Integer;
Line 1,645: Line 1,645:
tmp:=a[i]; a[i]:=a[j]; a[j]:=tmp;
tmp:=a[i]; a[i]:=a[j]; a[j]:=tmp;
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
<lang e>def shuffle(array, random) {
<syntaxhighlight lang="e">def shuffle(array, random) {
for bound in (2..(array.size())).descending() {
for bound in (2..(array.size())).descending() {
def i := random.nextInt(bound)
def i := random.nextInt(bound)
Line 1,656: Line 1,656:
array[i] := t
array[i] := t
}
}
}</lang>
}</syntaxhighlight>
<lang e>? def arr := [1,2,3,4,5,6,7,8,9,10].diverge()
<syntaxhighlight 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()
# value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].diverge()


? shuffle(arr, entropy)
? shuffle(arr, entropy)
? arr
? arr
# value: [4, 5, 2, 9, 7, 8, 1, 3, 6, 10].diverge()</lang>
# value: [4, 5, 2, 9, 7, 8, 1, 3, 6, 10].diverge()</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>func shuffle . a[] .
<syntaxhighlight lang="text">func shuffle . a[] .
for i = len a[] downto 2
for i = len a[] downto 2
r = random i
r = random i
Line 1,674: Line 1,674:
call shuffle arr[]
call shuffle arr[]
print arr[]
print arr[]
</syntaxhighlight>
</lang>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
Remark- The native '''shuffle''' function implementation in EchoLisp has been replaced by this one.
Remark- The native '''shuffle''' function implementation in EchoLisp has been replaced by this one.
Thx Rosetta Code.
Thx Rosetta Code.
Line 1,707: Line 1,707:
'(adrien 🎸 alexandre 🚂 antoine 🍼 ben 📚 georges 📷 julie 🎥 marine 🐼 nathalie 🍕 ))
'(adrien 🎸 alexandre 🚂 antoine 🍼 ben 📚 georges 📷 julie 🎥 marine 🐼 nathalie 🍕 ))
→ (antoine 🎥 🚂 marine adrien nathalie 🍼 🍕 ben 🐼 julie 📷 📚 🎸 alexandre georges)
→ (antoine 🎥 🚂 marine adrien nathalie 🍼 🍕 ben 🐼 julie 📷 📚 🎸 alexandre georges)
</syntaxhighlight>
</lang>


=={{header|Egel}}==
=={{header|Egel}}==
<syntaxhighlight lang="egel">
<lang Egel>
import "prelude.eg"
import "prelude.eg"
import "random.ego"
import "random.ego"
Line 1,728: Line 1,728:


def main = shuffle (fromto 1 9)
def main = shuffle (fromto 1 9)
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,788: Line 1,788:
end
end


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,797: Line 1,797:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x:
ELENA 4.x:
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
Line 1,824: Line 1,824:
console.printLine(a.randomize())
console.printLine(a.randomize())
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,832: Line 1,832:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Knuth do
<syntaxhighlight lang="elixir">defmodule Knuth do
def shuffle( inputs ) do
def shuffle( inputs ) do
n = length( inputs )
n = length( inputs )
Line 1,853: Line 1,853:
Map.update(acc, k, 1, &(&1+1))
Map.update(acc, k, 1, &(&1+1))
end)
end)
|> Enum.each(fn {k,v} -> IO.inspect {k,v} end)</lang>
|> Enum.each(fn {k,v} -> IO.inspect {k,v} end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,867: Line 1,867:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( knuth_shuffle ).
-module( knuth_shuffle ).


Line 1,882: Line 1,882:
Item = lists:nth( random:uniform(N), Inputs ),
Item = lists:nth( random:uniform(N), Inputs ),
{lists:delete(Item, Inputs), [Item | Acc]}.
{lists:delete(Item, Inputs), [Item | Acc]}.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,890: Line 1,890:


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang ERRE>PROGRAM KNUTH_SHUFFLE
<syntaxhighlight lang="erre">PROGRAM KNUTH_SHUFFLE


CONST CARDS%=52
CONST CARDS%=52
Line 1,909: Line 1,909:
PRINT
PRINT
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
{{trans|BASIC}}
{{trans|BASIC}}
<lang Euphoria>sequence cards
<syntaxhighlight lang="euphoria">sequence cards
cards = repeat(0,52)
cards = repeat(0,52)
integer card,temp
integer card,temp
Line 1,935: Line 1,935:
for i = 1 to 52 do
for i = 1 to 52 do
printf(1,"%d ",cards[i])
printf(1,"%d ",cards[i])
end for</lang>
end for</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
Line 1,941: Line 1,941:


This is the original Fisher-Yates shuffle as described by the link:
This is the original Fisher-Yates shuffle as described by the link:
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let FisherYatesShuffle (initialList : array<'a>) = // '
let FisherYatesShuffle (initialList : array<'a>) = // '
Line 1,957: Line 1,957:
initialList.[index] // and return the original item
initialList.[index] // and return the original item
seq {(initialList.Length) .. -1 .. 1} // Going from the length of the list down to 1
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</lang>
|> Seq.map (fun i -> nextItem i) // yield the next item</syntaxhighlight>
Here's the modified Knuth shuffle which shuffles the original array in place
Here's the modified Knuth shuffle which shuffles the original array in place
<lang fsharp>let KnuthShuffle (lst : array<'a>) = // '
<syntaxhighlight lang="fsharp">let KnuthShuffle (lst : array<'a>) = // '
let Swap i j = // Standard swap
let Swap i j = // Standard swap
let item = lst.[i]
let item = lst.[i]
Line 1,968: Line 1,968:
[0..(ln - 2)] // For all indices except the last
[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)
|> 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</lang>
lst // Return the list shuffled in place</syntaxhighlight>
Example:
Example:
<lang fsharp>> KnuthShuffle [| "Darrell"; "Marvin"; "Doug"; "Greg"; "Sam"; "Ken" |];;
<syntaxhighlight lang="fsharp">> KnuthShuffle [| "Darrell"; "Marvin"; "Doug"; "Greg"; "Sam"; "Ken" |];;
val it : string array = [|"Marvin"; "Doug"; "Sam"; "Darrell"; "Ken"; "Greg"|]</lang>
val it : string array = [|"Marvin"; "Doug"; "Sam"; "Darrell"; "Ken"; "Greg"|]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
There is a <code>randomize</code> word already in the standard library. Implementation:
There is a <code>randomize</code> word already in the standard library. Implementation:
<lang factor>: randomize ( seq -- seq )
<syntaxhighlight lang="factor">: randomize ( seq -- seq )
dup length [ dup 1 > ]
dup length [ dup 1 > ]
[ [ iota random ] [ 1 - ] bi [ pick exchange ] keep ]
[ [ iota random ] [ 1 - ] bi [ pick exchange ] keep ]
while drop ;</lang>
while drop ;</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
<lang fantom>class Main
<syntaxhighlight lang="fantom">class Main
{
{
static Void knuthShuffle (List array)
static Void knuthShuffle (List array)
Line 2,002: Line 2,002:
echo (b)
echo (b)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>include random.fs
<syntaxhighlight lang="forth">include random.fs


: shuffle ( deck size -- )
: shuffle ( deck size -- )
Line 2,019: Line 2,019:
create deck 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,
create deck 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,


deck 10 2dup shuffle .array</lang>
deck 10 2dup shuffle .array</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>program Knuth_Shuffle
<syntaxhighlight lang="fortran">program Knuth_Shuffle
implicit none
implicit none


Line 2,055: Line 2,055:
end subroutine Shuffle
end subroutine Shuffle
end program Knuth_Shuffle</lang>
end program Knuth_Shuffle</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' version 22-10-2016
<syntaxhighlight lang="freebasic">' version 22-10-2016
' compile with: fbc -s console
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
' for boundry checks on array's compile with: fbc -s console -exx
Line 2,134: Line 2,134:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>Starting array
<pre>Starting array
Line 2,154: Line 2,154:
=={{header|Frink}}==
=={{header|Frink}}==
The built-in method <CODE><I>array</I>.shuffle[]</CODE> implements the Fisher-Yates-Knuth shuffle algorithm:
The built-in method <CODE><I>array</I>.shuffle[]</CODE> implements the Fisher-Yates-Knuth shuffle algorithm:
<lang frink>
<syntaxhighlight lang="frink">
a = [1,2,3]
a = [1,2,3]
a.shuffle[]
a.shuffle[]
</syntaxhighlight>
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>def shuffle( a ) =
<syntaxhighlight lang="funl">def shuffle( a ) =
res = array( a )
res = array( a )
n = a.length()
n = a.length()
Line 2,168: Line 2,168:
res(i), res(r) = res(r), res(i)
res(i), res(r) = res(r), res(i)
res.toList()</lang>
res.toList()</syntaxhighlight>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=58402023fbdc617ce10f6a85db721105 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=58402023fbdc617ce10f6a85db721105 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim iTotal As Integer = 40
Dim iTotal As Integer = 40
Dim iCount, iRand1, iRand2 As Integer
Dim iCount, iRand1, iRand2 As Integer
Line 2,197: Line 2,197:
Next
Next


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,205: Line 2,205:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Return the list L after applying Knuth shuffle. GAP also has the function Shuffle, which does the same.
<syntaxhighlight lang="gap"># Return the list L after applying Knuth shuffle. GAP also has the function Shuffle, which does the same.
ShuffleAlt := function(a)
ShuffleAlt := function(a)
local i, j, n, t;
local i, j, n, t;
Line 2,230: Line 2,230:
# One may also call the built-in random generator on the symmetric group :
# One may also call the built-in random generator on the symmetric group :
Random(SymmetricGroup(10));
Random(SymmetricGroup(10));
(1,8,2,5,9,6)(3,4,10,7)</lang>
(1,8,2,5,9,6)(3,4,10,7)</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 2,238: Line 2,238:
implementing a Fisher–Yates shuffle.)
implementing a Fisher–Yates shuffle.)


<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,259: Line 2,259:
}
}
fmt.Println(a)
fmt.Println(a)
}</lang>
}</syntaxhighlight>
To shuffle any type:
To shuffle any type:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,308: Line 2,308:
shuffle(a)
shuffle(a)
fmt.Println(a)
fmt.Println(a)
}</lang>
}</syntaxhighlight>
{{out|Example output}} (of either program)
{{out|Example output}} (of either program)
<pre>
<pre>
Line 2,317: Line 2,317:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def shuffle = { list ->
<syntaxhighlight lang="groovy">def shuffle = { list ->
if (list == null || list.empty) return list
if (list == null || list.empty) return list
def r = new Random()
def r = new Random()
Line 2,326: Line 2,326:
}
}
list
list
}</lang>
}</syntaxhighlight>
Test:
Test:
<lang groovy>def list = [] + (0..20)
<syntaxhighlight lang="groovy">def list = [] + (0..20)
println list
println list
println shuffle(list)
println shuffle(list)
println shuffle(list)
println shuffle(list)
println shuffle(list)</lang>
println shuffle(list)</syntaxhighlight>
{{out}}
{{out}}
<pre>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
<pre>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Line 2,340: Line 2,340:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>import System.Random (randomRIO)
<syntaxhighlight lang="haskell">import System.Random (randomRIO)


mkRands :: Int -> IO [Int]
mkRands :: Int -> IO [Int]
Line 2,356: Line 2,356:


knuthShuffle :: [a] -> IO [a]
knuthShuffle :: [a] -> IO [a]
knuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> mkRands (length xs)</lang>
knuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> mkRands (length xs)</syntaxhighlight>


or, as an alternative to making two indexed references into the list with '''(!!)''':
or, as an alternative to making two indexed references into the list with '''(!!)''':
<lang haskell>import System.Random (randomRIO)
<syntaxhighlight lang="haskell">import System.Random (randomRIO)
import Data.Bool (bool)
import Data.Bool (bool)


Line 2,380: Line 2,380:


main :: IO ()
main :: IO ()
main = knuthShuffle ['a' .. 'k'] >>= print</lang>
main = knuthShuffle ['a' .. 'k'] >>= print</syntaxhighlight>


Examples of use of either of the two versions above:
Examples of use of either of the two versions above:
Line 2,389: Line 2,389:
[(0,10),(8,18),(2,12),(3,13),(9,19),(4,14),(7,17),(1,11),(6,16),(5,15)]</pre>
[(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:
Function for showing intermediate results:
<lang Haskell>knuthShuffleProcess :: (Show a) => [a] -> IO ()
<syntaxhighlight lang="haskell">knuthShuffleProcess :: (Show a) => [a] -> IO ()
knuthShuffleProcess =
knuthShuffleProcess =
(mapM_ print. reverse =<<). ap (fmap. (. zip [1..]). scanr swapElems) (mkRands. length)</lang>
(mapM_ print. reverse =<<). ap (fmap. (. zip [1..]). scanr swapElems) (mkRands. length)</syntaxhighlight>
{{out}} Detailed example:
{{out}} Detailed example:
<pre>*Main> knuthShuffleProcess ['a'..'k']
<pre>*Main> knuthShuffleProcess ['a'..'k']
Line 2,406: Line 2,406:
"iebjhkcgfad"</pre>
"iebjhkcgfad"</pre>
An imperative implementation using arrays and the <code>ST</code> monad:
An imperative implementation using arrays and the <code>ST</code> monad:
<lang haskell>import Data.Array.ST
<syntaxhighlight lang="haskell">import Data.Array.ST
import Data.STRef
import Data.STRef
import Control.Monad
import Control.Monad
Line 2,426: Line 2,426:
where len = length list
where len = length list
newAry :: (Int, Int) -> [a] -> ST s (STArray s Int a)
newAry :: (Int, Int) -> [a] -> ST s (STArray s Int a)
newAry = newListArray</lang>
newAry = newListArray</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The <tt>shuffle</tt> method used here can shuffle lists, record fields, and strings:
The <tt>shuffle</tt> method used here can shuffle lists, record fields, and strings:
<lang icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
show(shuffle([3,1,4,1,5,9,2,6,3]))
show(shuffle([3,1,4,1,5,9,2,6,3]))
show(shuffle("this is a string"))
show(shuffle("this is a string"))
Line 2,443: Line 2,443:
every writes(!A," ")
every writes(!A," ")
write()
write()
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>->ks
<pre>->ks
Line 2,450: Line 2,450:
-></pre>
-></pre>
Note that the gloriously succinct 'standard' Icon shuffle:
Note that the gloriously succinct 'standard' Icon shuffle:
<lang icon>procedure shuffle(A)
<syntaxhighlight lang="icon">procedure shuffle(A)
every !A :=: ?A
every !A :=: ?A
end</lang>
end</syntaxhighlight>
is subtly biased.
is subtly biased.


=={{header|Inform 6}}==
=={{header|Inform 6}}==
<lang Inform 6>[ shuffle a n i j tmp;
<syntaxhighlight lang="inform 6">[ shuffle a n i j tmp;
for(i = n - 1: i > 0: i--)
for(i = n - 1: i > 0: i--)
{
{
Line 2,465: Line 2,465:
a->i = tmp;
a->i = tmp;
}
}
];</lang>
];</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>KS=:{~ (2&{.@[ {`(|.@[)`]} ])/@(,~(,.?@>:))@i.@#</lang>
<syntaxhighlight lang="j">KS=:{~ (2&{.@[ {`(|.@[)`]} ])/@(,~(,.?@>:))@i.@#</syntaxhighlight>
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.
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.
<lang j>process J
<syntaxhighlight lang="j">process J


fold swap transform array <==> f / g y</lang>
fold swap transform array <==> f / g y</syntaxhighlight>
Example of a transformed input:
Example of a transformed input:
<lang j>(,~(,.?@>:))@i.@# 1+i.6
<syntaxhighlight lang="j">(,~(,.?@>:))@i.@# 1+i.6
0 0 0 0 0 0
0 0 0 0 0 0
1 1 0 0 0 0
1 1 0 0 0 0
Line 2,481: Line 2,481:
4 3 0 0 0 0
4 3 0 0 0 0
5 0 0 0 0 0
5 0 0 0 0 0
0 1 2 3 4 5</lang>
0 1 2 3 4 5</syntaxhighlight>
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 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:
The index-swapping is done by the part:
<lang j>2&{.@[ {`(|.@[)`]} ]</lang>
<syntaxhighlight lang="j">2&{.@[ {`(|.@[)`]} ]</syntaxhighlight>
Finally, the shuffled indexes select elements from the original array.
Finally, the shuffled indexes select elements from the original array.
<lang j>input { ~ shuffled indexes</lang>
<syntaxhighlight lang="j">input { ~ shuffled indexes</syntaxhighlight>
Alternatively, instead of creating a rectangular array, the swapping indices and the original data can be individually boxed.
Alternatively, instead of creating a rectangular array, the swapping indices and the original data can be individually boxed.


Line 2,493: Line 2,493:


With this approach, the data structure with the swapping indices and the original data could look like this:
With this approach, the data structure with the swapping indices and the original data could look like this:
<lang j> (|.@; ;&~./@(,. ?@>:)@i.@#)'abcde'
<syntaxhighlight lang="j"> (|.@; ;&~./@(,. ?@>:)@i.@#)'abcde'
+---+-+---+---+-+-----+
+---+-+---+---+-+-----+
|4 2|3|2 1|1 0|0|abcde|
|4 2|3|2 1|1 0|0|abcde|
+---+-+---+---+-+-----+</lang>
+---+-+---+---+-+-----+</syntaxhighlight>
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>)).
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:
The resulting definition looks like this:
<lang j>KS=: [: > (<@C. >)/@(|.@; ;&~./@(,. ?@>:)@i.@#)</lang>
<syntaxhighlight lang="j">KS=: [: > (<@C. >)/@(|.@; ;&~./@(,. ?@>:)@i.@#)</syntaxhighlight>
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.
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.
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:<lang j>]A=: 5+i.9
Examples:<syntaxhighlight lang="j">]A=: 5+i.9
5 6 7 8 9 10 11 12 13</lang> Shuffle:
5 6 7 8 9 10 11 12 13</syntaxhighlight> Shuffle:
<lang j>KS A
<syntaxhighlight lang="j">KS A
13 10 7 5 11 9 8 6 12</lang>Input
13 10 7 5 11 9 8 6 12</syntaxhighlight>Input
<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
<syntaxhighlight 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 1 1
1 0 0
1 0 0
Line 2,520: Line 2,520:


11 2 3
11 2 3
0 11 2</lang>Shuffle
0 11 2</syntaxhighlight>Shuffle
<lang j>KS M
<syntaxhighlight lang="j">KS M
11 2 3
11 2 3
0 11 2
0 11 2
Line 2,532: Line 2,532:


1 2 3
1 2 3
2 3 4</lang>Input
2 3 4</syntaxhighlight>Input
<lang j>]L=:'aA';'bbB';'cC%$';'dD@'
<syntaxhighlight lang="j">]L=:'aA';'bbB';'cC%$';'dD@'
+--+---+----+---+
+--+---+----+---+
|aA|bbB|cC%$|dD@|
|aA|bbB|cC%$|dD@|
+--+---+----+---+</lang>Shuffle
+--+---+----+---+</syntaxhighlight>Shuffle
<lang j>KS L
<syntaxhighlight lang="j">KS L
+--+----+---+---+
+--+----+---+---+
|aA|cC%$|dD@|bbB|
|aA|cC%$|dD@|bbB|
+--+----+---+---+</lang>
+--+----+---+---+</syntaxhighlight>
In J the shuffling of an arbitrary array can easily be implemented by the phrase
In J the shuffling of an arbitrary array can easily be implemented by the phrase
( ref http://www.jsoftware.com/jwiki/JPhrases/RandomNumbers ):
( ref http://www.jsoftware.com/jwiki/JPhrases/RandomNumbers ):
<lang j>({~?~@#)</lang>
<syntaxhighlight lang="j">({~?~@#)</syntaxhighlight>
Applied on the former examples:
Applied on the former examples:
<lang j>({~?~@#) A
<syntaxhighlight lang="j">({~?~@#) A
8 7 13 6 10 11 5 9 12
8 7 13 6 10 11 5 9 12


Line 2,564: Line 2,564:
+----+---+--+---+
+----+---+--+---+
|cC%$|bbB|aA|dD@|
|cC%$|bbB|aA|dD@|
+----+---+--+---+</lang>
+----+---+--+---+</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.Random;
<syntaxhighlight lang="java">import java.util.Random;


public static final Random gen = new Random();
public static final Random gen = new Random();
Line 2,590: Line 2,590:
array[k] = temp;
array[k] = temp;
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 2,596: Line 2,596:
===ES5===
===ES5===


<lang javascript>function knuthShuffle(arr) {
<syntaxhighlight lang="javascript">function knuthShuffle(arr) {
var rand, temp, i;
var rand, temp, i;


Line 2,620: Line 2,620:
for (var key in res) {
for (var key in res) {
print(key + "\t" + res[key]);
print(key + "\t" + res[key]);
}</lang>
}</syntaxhighlight>
Results in:
Results in:
<pre>1,2,3 16619
<pre>1,2,3 16619
Line 2,633: Line 2,633:


====Mutating in-place swap====
====Mutating in-place swap====
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// knuthShuffle :: [a] -> [a]
// knuthShuffle :: [a] -> [a]
Line 2,679: Line 2,679:
return test();
return test();
})();
})();
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
e.g.
e.g.
<lang JavaScript>["iota", "epsilon", "kappa", "theta", "gamma", "delta",
<syntaxhighlight lang="javascript">["iota", "epsilon", "kappa", "theta", "gamma", "delta",
"lambda", "eta", "zeta", "beta", "mu", "alpha"]</lang>
"lambda", "eta", "zeta", "beta", "mu", "alpha"]</syntaxhighlight>


====Non-mutating swap====
====Non-mutating swap====
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// knuthShuffle :: [a] -> [a]
// knuthShuffle :: [a] -> [a]
Line 2,747: Line 2,747:
// MAIN ---
// MAIN ---
return test();
return test();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
e.g.
e.g.
<lang JavaScript>["mu", "theta", "beta", "eta", "delta", "epsilon",
<syntaxhighlight lang="javascript">["mu", "theta", "beta", "eta", "delta", "epsilon",
"kappa", "alpha", "gamma", "lambda", "zeta", "iota"]</lang>
"kappa", "alpha", "gamma", "lambda", "zeta", "iota"]</syntaxhighlight>


=={{header|Joy}}==
=={{header|Joy}}==
<syntaxhighlight lang=Joy>DEFINE knuth-shuffle ==
<syntaxhighlight lang="joy">DEFINE knuth-shuffle ==
(* Take the size of the array (without destroying it) *)
(* Take the size of the array (without destroying it) *)
dup dup size
dup dup size
Line 2,767: Line 2,767:
[second] map.</syntaxhighlight>
[second] map.</syntaxhighlight>
Using knuth-shuffle (file shuffle.joy):
Using knuth-shuffle (file shuffle.joy):
<syntaxhighlight lang=Joy>(* Sorted array of 21 integers *)
<syntaxhighlight lang="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]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
knuth-shuffle.</syntaxhighlight>
knuth-shuffle.</syntaxhighlight>
Line 2,793: Line 2,793:


where program.jq is the following program:
where program.jq is the following program:
<syntaxhighlight lang="jq">
<lang jq>
# 52-card deck:
# 52-card deck:
def deck:
def deck:
Line 2,837: Line 2,837:
task,
task,
(deck|knuthShuffle | nwise(13) | implode)
(deck|knuthShuffle | nwise(13) | implode)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,854: Line 2,854:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>function knuthshuffle!(r::AbstractRNG, v::AbstractVector)
<syntaxhighlight lang="julia">function knuthshuffle!(r::AbstractRNG, v::AbstractVector)
for i in length(v):-1:2
for i in length(v):-1:2
j = rand(r, 1:i)
j = rand(r, 1:i)
Line 2,864: Line 2,864:


v = collect(1:20)
v = collect(1:20)
println("# v = $v\n -> ", knuthshuffle!(v))</lang>
println("# v = $v\n -> ", knuthshuffle!(v))</syntaxhighlight>


{{out}}
{{out}}
Line 2,871: Line 2,871:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>object Knuth {
<syntaxhighlight lang="scala">object Knuth {
internal val gen = java.util.Random()
internal val gen = java.util.Random()
}
}
Line 2,901: Line 2,901:
require(s.toSortedSet() == ia.toSet())
require(s.toSortedSet() == ia.toSet())
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>xdhsvtnumjgbywiqoapcelkrfz
<pre>xdhsvtnumjgbywiqoapcelkrfz
Line 2,930: Line 2,930:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{def shuffle
{def shuffle


Line 2,960: Line 2,960:
{shuffle {B}}
{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]
-> [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}}==
=={{header|Lasso}}==
<lang lasso>define staticarray->swap(p1::integer,p2::integer) => {
<syntaxhighlight lang="lasso">define staticarray->swap(p1::integer,p2::integer) => {
fail_if(
fail_if(
#p1 < 1 or #p2 < 1 or
#p1 < 1 or #p2 < 1 or
Line 2,982: Line 2,982:
}
}


(1 to 10)->asStaticArray->knuthShuffle&asString</lang>
(1 to 10)->asStaticArray->knuthShuffle&asString</syntaxhighlight>
{{out}}
{{out}}
<pre>staticarray(9, 5, 6, 1, 10, 8, 3, 4, 2, 7)</pre>
<pre>staticarray(9, 5, 6, 1, 10, 8, 3, 4, 2, 7)</pre>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>'Declared the UpperBound to prevent confusion with lots of 9's floating around....
<syntaxhighlight lang="lb">'Declared the UpperBound to prevent confusion with lots of 9's floating around....
UpperBound = 9
UpperBound = 9
Dim array(UpperBound)
Dim array(UpperBound)
Line 3,008: Line 3,008:
For i = 0 To UpperBound
For i = 0 To UpperBound
Print array(i)
Print array(i)
Next i</lang>
Next i</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to swap :i :j :a
<syntaxhighlight lang="logo">to swap :i :j :a
localmake "t item :i :a
localmake "t item :i :a
setitem :i :a item :j :a
setitem :i :a item :j :a
Line 3,022: Line 3,022:
make "a {1 2 3 4 5 6 7 8 9 10}
make "a {1 2 3 4 5 6 7 8 9 10}
shuffle :a
shuffle :a
show :a</lang>
show :a</syntaxhighlight>
Lhogho does not have a setitem, and also does things more 'function'ally.
Lhogho does not have a setitem, and also does things more 'function'ally.
<lang logo>to slice :lst :start :finish
<syntaxhighlight lang="logo">to slice :lst :start :finish
local "res
local "res
make "res []
make "res []
Line 3,060: Line 3,060:
make "a ( list 1 2 3 4 5 6 7 8 9 10 )
make "a ( list 1 2 3 4 5 6 7 8 9 10 )
make "a shuffle :a
make "a shuffle :a
show :a</lang>
show :a</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function table.shuffle(t)
<syntaxhighlight lang="lua">function table.shuffle(t)
for n = #t, 1, -1 do
for n = #t, 1, -1 do
local k = math.random(n)
local k = math.random(n)
Line 3,075: Line 3,075:
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
table.shuffle(a)
table.shuffle(a)
for i,v in ipairs(a) do print(i,v) end</lang>
for i,v in ipairs(a) do print(i,v) end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Dim Base 0, A(3)
Dim Base 0, A(3)
For k=1 to 6 {
For k=1 to 6 {
Line 3,089: Line 3,089:
}
}


</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>divert(-1)
<syntaxhighlight lang="m4">divert(-1)
define(`randSeed',141592653)
define(`randSeed',141592653)
define(`rand_t',`eval(randSeed^(randSeed>>13))')
define(`rand_t',`eval(randSeed^(randSeed>>13))')
Line 3,118: Line 3,118:
show(`b')
show(`b')
shuffle(`b')
shuffle(`b')
show(`b')</lang>
show(`b')</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,132: Line 3,132:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Usage of built-in function:
Usage of built-in function:
<lang Mathematica>RandomSample[{1, 2, 3, 4, 5, 6}]</lang>
<syntaxhighlight lang="mathematica">RandomSample[{1, 2, 3, 4, 5, 6}]</syntaxhighlight>
Custom function:
Custom function:
<lang Mathematica>Shuffle[input_List /; Length[input] >= 1] :=
<syntaxhighlight lang="mathematica">Shuffle[input_List /; Length[input] >= 1] :=
Module[{indices = {}, allindices = Range[Length[input]]},
Module[{indices = {}, allindices = Range[Length[input]]},
Do[
Do[
Line 3,143: Line 3,143:
];
];
input[[indices]]
input[[indices]]
]</lang>
]</syntaxhighlight>
Example:
Example:
<lang Mathematica>Shuffle[{1, 2, 3, 4, 5, 6}]</lang>
<syntaxhighlight lang="mathematica">Shuffle[{1, 2, 3, 4, 5, 6}]</syntaxhighlight>


=={{header|MATLAB}}==
=={{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.
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.
<lang MATLAB>function list = knuthShuffle(list)
<syntaxhighlight lang="matlab">function list = knuthShuffle(list)


for i = (numel(list):-1:2)
for i = (numel(list):-1:2)
Line 3,158: Line 3,158:
list([j i]) = list([i j]);
list([j i]) = list([i j]);
end
end
end</lang>
end</syntaxhighlight>
There is an alternate way to do this that is not a true Knuth Shuffle, but operates with the same spirit.
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,
This alternate version produces the same output, saves some space,
and can be implemented in-line without the need to encapsulate it
and can be implemented in-line without the need to encapsulate it
in a function call like the Knuth Shuffle.
in a function call like the Knuth Shuffle.
<lang MATLAB>function list = randSort(list)
<syntaxhighlight lang="matlab">function list = randSort(list)
list = list( randperm(numel(list)) );
list = list( randperm(numel(list)) );
end</lang>
end</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* Maxima has an implementation of Knuth shuffle */
<syntaxhighlight lang="maxima">/* Maxima has an implementation of Knuth shuffle */
random_permutation([a, b, c]);</lang>
random_permutation([a, b, c]);</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Shuffle EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Shuffle EXPORTS Main;


IMPORT IO, Fmt, Random;
IMPORT IO, Fmt, Random;
Line 3,202: Line 3,202:
END;
END;
IO.Put("\n");
IO.Put("\n");
END Shuffle.</lang>
END Shuffle.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,212: Line 3,212:


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>Shuffle(items,separator) New ii,item,list,n
<syntaxhighlight lang="mumps">Shuffle(items,separator) New ii,item,list,n
Set list="",n=0
Set list="",n=0
Set ii="" For Set ii=$Order(items(ii)) Quit:ii="" Do
Set ii="" For Set ii=$Order(items(ii)) Quit:ii="" Do
Line 3,295: Line 3,295:
Queen of Spades
Queen of Spades
King of Diamonds
King of Diamonds
5 of Clubs</lang>
5 of Clubs</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>Shuffle[T] (arr : array[T]) : array[T]
<syntaxhighlight lang="nemerle">Shuffle[T] (arr : array[T]) : array[T]
{
{
def rnd = Random();
def rnd = Random();
Line 3,305: Line 3,305:
arr[i] <-> arr[(rnd.Next(i, arr.Length))];
arr[i] <-> arr[(rnd.Next(i, arr.Length))];
arr
arr
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
===version 1===
===version 1===
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary


Line 3,357: Line 3,357:
say
say


return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,372: Line 3,372:


===version 2===
===version 2===
<lang NetRexx>/* NetRexx ------------------------------------------------------------
<syntaxhighlight lang="netrexx">/* NetRexx ------------------------------------------------------------
* 08.01.2014 Walter Pachl modified to show state development a la Rexx
* 08.01.2014 Walter Pachl modified to show state development a la Rexx
*--------------------------------------------------------------------*/
*--------------------------------------------------------------------*/
Line 3,405: Line 3,405:
method showHand(deck = ArrayList,tag=REXX) public static binary
method showHand(deck = ArrayList,tag=REXX) public static binary
say tag ArrayList(deck.subList(0,deck.size)).toString
say tag ArrayList(deck.subList(0,deck.size)).toString
return</lang>
return</syntaxhighlight>
{{out}}
{{out}}
<pre>In [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
<pre>In [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Line 3,421: Line 3,421:
=={{header|Nim}}==
=={{header|Nim}}==
Note that the function "shuffle" exists in the standard module "random" and that it uses the Knuth shuffle.
Note that the function "shuffle" exists in the standard module "random" and that it uses the Knuth shuffle.
<lang nim>import random
<syntaxhighlight lang="nim">import random
randomize()
randomize()


Line 3,431: Line 3,431:
var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shuffle(x)
shuffle(x)
echo x</lang>
echo x</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


@interface NSMutableArray (KnuthShuffle)
@interface NSMutableArray (KnuthShuffle)
Line 3,455: Line 3,455:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,473: Line 3,473:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let shuffle arr =
<syntaxhighlight lang="ocaml">let shuffle arr =
for n = Array.length arr - 1 downto 1 do
for n = Array.length arr - 1 downto 1 do
let k = Random.int (n + 1) in
let k = Random.int (n + 1) in
Line 3,479: Line 3,479:
arr.(n) <- arr.(k);
arr.(n) <- arr.(k);
arr.(k) <- temp
arr.(k) <- temp
done</lang>
done</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 3,486: Line 3,486:
Returns a new list
Returns a new list


<lang Oforth>Indexable method: shuffle
<syntaxhighlight lang="oforth">Indexable method: shuffle
| s i l |
| s i l |
self asListBuffer ->l
self asListBuffer ->l
self size dup ->s 1- loop: i [ s i - rand i + i l swapValues ]
self size dup ->s 1- loop: i [ s i - rand i + i l swapValues ]
l dup freeze ; </lang>
l dup freeze ; </syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Line 3,497: Line 3,497:
Ol is functional language, so we should make a copy of shuffling tuple and return this shuffled copy.
Ol is functional language, so we should make a copy of shuffling tuple and return this shuffled copy.


<lang scheme>
<syntaxhighlight lang="scheme">
(define (shuffle tp)
(define (shuffle tp)
(let ((items (vm:cast tp (type tp)))) ; make a copy
(let ((items (vm:cast tp (type tp)))) ; make a copy
Line 3,513: Line 3,513:
(tuple->list
(tuple->list
(shuffle (list->tuple (iota (length tp)))))))
(shuffle (list->tuple (iota (length tp)))))))
</syntaxhighlight>
</lang>


Testing:
Testing:
<lang scheme>
<syntaxhighlight lang="scheme">
(define items (tuple 1 2 3 4 5 6 7 8 9))
(define items (tuple 1 2 3 4 5 6 7 8 9))
(print "tuple before: " items)
(print "tuple before: " items)
Line 3,524: Line 3,524:
(print "list before: " items)
(print "list before: " items)
(print "list after: " (list-shuffle items))
(print "list after: " (list-shuffle items))
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,534: Line 3,534:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
proc {Shuffle Arr}
proc {Shuffle Arr}
Low = {Array.low Arr}
Low = {Array.low Arr}
Line 3,552: Line 3,552:
{Show {Array.toRecord unit X}}
{Show {Array.toRecord unit X}}
{Shuffle X}
{Shuffle X}
{Show {Array.toRecord unit X}}</lang>
{Show {Array.toRecord unit X}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>FY(v)={
<syntaxhighlight lang="parigp">FY(v)={
forstep(n=#v,2,-1,
forstep(n=#v,2,-1,
my(i=random(n)+1,t=v[i]);
my(i=random(n)+1,t=v[i]);
Line 3,564: Line 3,564:
};
};


FY(vector(52,i,i))</lang>
FY(vector(52,i,i))</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang Pascal>program Knuth;
<syntaxhighlight lang="pascal">program Knuth;


const
const
Line 3,618: Line 3,618:
DisplayList(a);
DisplayList(a);
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre> -5 -4 -3 -2 -1 0 1 2 3 4 5
<pre> -5 -4 -3 -2 -1 0 1 2 3 4 5
Line 3,629: Line 3,629:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub shuffle {
<syntaxhighlight lang="perl">sub shuffle {
my @a = @_;
my @a = @_;
foreach my $n (1 .. $#a) {
foreach my $n (1 .. $#a) {
Line 3,636: Line 3,636:
}
}
return @a;
return @a;
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="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: #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>
<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,648: Line 3,648:
<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;">"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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre style="font-size: 12px">
<pre style="font-size: 12px">
Line 3,657: Line 3,657:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>//The Fisher-Yates original Method
<syntaxhighlight lang="php">//The Fisher-Yates original Method
function yates_shuffle($arr){
function yates_shuffle($arr){
$shuffled = Array();
$shuffled = Array();
Line 3,674: Line 3,674:
list($arr[$i], $arr[$rnd]) = array($arr[$rnd], $arr[$i]);
list($arr[$i], $arr[$rnd]) = array($arr[$rnd], $arr[$i]);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
_ = random2(),
_ = random2(),
L = 1..10,
L = 1..10,
Line 3,691: Line 3,691:
L[I] := L[J],
L[I] := L[J],
L[J] := Tmp
L[J] := Tmp
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 3,698: Line 3,698:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(seed (in "/dev/urandom" (rd 8)))
<syntaxhighlight lang="picolisp">(seed (in "/dev/urandom" (rd 8)))


(de knuth (Lst)
(de knuth (Lst)
Line 3,708: Line 3,708:
(println 'before L)
(println 'before L)
(knuth L)
(knuth L)
(println 'after L) )</lang>
(println 'after L) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,717: Line 3,717:
=={{header|PL/I}}==
=={{header|PL/I}}==
===version 1===
===version 1===
<lang pli>declare T(0:10) fixed binary initial (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
<syntaxhighlight 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;
declare (i, j, temp) fixed binary;
do i = lbound(T,1) to hbound(T,1);
do i = lbound(T,1) to hbound(T,1);
j = min(random() * 12, 11);
j = min(random() * 12, 11);
temp = T(j); T(j) = T(i); T(i) = temp;
temp = T(j); T(j) = T(i); T(i) = temp;
end;</lang>
end;</syntaxhighlight>


===version 2===
===version 2===
<lang pli> kn: Proc Options(main);
<syntaxhighlight lang="pli"> kn: Proc Options(main);
/*--------------------------------------------------------------------
/*--------------------------------------------------------------------
* 07.01.2014 Walter Pachl translated from REXX version 2
* 07.01.2014 Walter Pachl translated from REXX version 2
Line 3,747: Line 3,747:
Put Edit(txt,(t(k) do k=1 To n))(Skip,a(7),10(f(3)));
Put Edit(txt,(t(k) do k=1 To n))(Skip,a(7),10(f(3)));
End;
End;
end;</lang>
end;</syntaxhighlight>
{{out}}
{{out}}
<pre>In 1 2 3 4 5 6 7 8 9 10
<pre>In 1 2 3 4 5 6 7 8 9 10
Line 3,763: Line 3,763:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|3}}
{{works with|PowerShell|3}}
<lang powershell>$A = 1, 2, 3, 4, 5
<syntaxhighlight lang="powershell">$A = 1, 2, 3, 4, 5
Get-Random $A -Count $A.Count</lang>
Get-Random $A -Count $A.Count</syntaxhighlight>
{{works with|PowerShell|2}} <!-- Get-Random didn't exist in PowerShell 1 -->
{{works with|PowerShell|2}} <!-- Get-Random didn't exist in PowerShell 1 -->
<lang powershell>function shuffle ($a) {
<syntaxhighlight lang="powershell">function shuffle ($a) {
$c = $a.Clone() # make copy to avoid clobbering $a
$c = $a.Clone() # make copy to avoid clobbering $a
1..($c.Length - 1) | ForEach-Object {
1..($c.Length - 1) | ForEach-Object {
Line 3,774: Line 3,774:
}
}
$c[-1] # last value
$c[-1] # last value
}</lang>
}</syntaxhighlight>
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.
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}}==
=={{header|PureBasic}}==
<lang PureBasic>EnableExplicit
<syntaxhighlight lang="purebasic">EnableExplicit


Procedure KnuthShuffle(Array a(1))
Procedure KnuthShuffle(Array a(1))
Line 3,809: Line 3,809:


KnuthShuffle(a())
KnuthShuffle(a())
Debug "shuffled: " + ArrayToString(a())</lang>
Debug "shuffled: " + ArrayToString(a())</syntaxhighlight>
{{out}}
{{out}}
<pre>shuffled: 1,8,6,0,5,9,2,4,7,3</pre>
<pre>shuffled: 1,8,6,0,5,9,2,4,7,3</pre>
Line 3,816: Line 3,816:
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.
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:
The function below is very similar:
<lang python>from random import randrange
<syntaxhighlight lang="python">from random import randrange


def knuth_shuffle(x):
def knuth_shuffle(x):
Line 3,825: Line 3,825:
x = list(range(10))
x = list(range(10))
knuth_shuffle(x)
knuth_shuffle(x)
print("shuffled:", x)</lang>
print("shuffled:", x)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,834: Line 3,834:
We could also write our own Knuth shuffle function as a fold, with a non-mutating swap function:
We could also write our own Knuth shuffle function as a fold, with a non-mutating swap function:
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Knuth shuffle as a fold'''
<syntaxhighlight lang="python">'''Knuth shuffle as a fold'''


from functools import reduce
from functools import reduce
Line 3,928: Line 3,928:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Repeated Knuth shuffles of ['a' .. 'k']:
<pre>Repeated Knuth shuffles of ['a' .. 'k']:
Line 3,948: Line 3,948:
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.)
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.)


<lang Quackery> [ [] swap dup size times
<syntaxhighlight lang="quackery"> [ [] swap dup size times
[ dup size random pluck
[ dup size random pluck
nested rot join swap ]
nested rot join swap ]
Line 3,968: Line 3,968:
[ dup size 1 - times
[ dup size 1 - times
[ i 1+ dup 1+ random
[ i 1+ dup 1+ random
rot [exch] ] ] is knuffle ( [ --> [ )</lang>
rot [exch] ] ] is knuffle ( [ --> [ )</syntaxhighlight>


{{out}}
{{out}}
Line 4,010: Line 4,010:
===Original Fisher-Yates version===
===Original Fisher-Yates version===
<lang rsplus>fisheryatesshuffle <- function(n)
<syntaxhighlight lang="rsplus">fisheryatesshuffle <- function(n)
{
{
pool <- seq_len(n)
pool <- seq_len(n)
Line 4,021: Line 4,021:
}
}
a
a
}</lang>
}</syntaxhighlight>
===Knuth variation===
===Knuth variation===
<lang rsplus>fisheryatesknuthshuffle <- function(n)
<syntaxhighlight lang="rsplus">fisheryatesknuthshuffle <- function(n)
{
{
a <- seq_len(n)
a <- seq_len(n)
Line 4,043: Line 4,043:
fisheryatesshuffle(6) # e.g. 1 3 6 2 4 5
fisheryatesshuffle(6) # e.g. 1 3 6 2 4 5
x <- c("foo", "bar", "baz", "quux")
x <- c("foo", "bar", "baz", "quux")
x[fisheryatesknuthshuffle(4)] # e.g. "bar" "baz" "quux" "foo"</lang>
x[fisheryatesknuthshuffle(4)] # e.g. "bar" "baz" "quux" "foo"</syntaxhighlight>
===Short version===
===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:
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:
<lang rsplus>knuth <- function(vec)
<syntaxhighlight lang="rsplus">knuth <- function(vec)
{
{
last <- length(vec)
last <- length(vec)
Line 4,064: Line 4,064:
replicate(10, knuth(c(10, 20)))
replicate(10, knuth(c(10, 20)))
replicate(10, knuth(c(10, 20, 30)))
replicate(10, knuth(c(10, 20, 30)))
knuth(c("Also", "works", "for", "strings"))</lang>
knuth(c("Also", "works", "for", "strings"))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>> knuth(integer(0))
<pre>> knuth(integer(0))
Line 4,084: Line 4,084:
=={{header|Racket}}==
=={{header|Racket}}==


<lang scheme>#lang racket
<syntaxhighlight lang="scheme">#lang racket


(define (swap! vec i j)
(define (swap! vec i j)
Line 4,099: Line 4,099:
x)))
x)))


(knuth-shuffle '(1 2 3 4))</lang>
(knuth-shuffle '(1 2 3 4))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|#21 "Seattle"}}
{{works with|Rakudo|#21 "Seattle"}}
<lang perl6>sub shuffle (@a is copy) {
<syntaxhighlight lang="raku" line>sub shuffle (@a is copy) {
for 1 ..^ @a -> $n {
for 1 ..^ @a -> $n {
my $k = (0 .. $n).pick;
my $k = (0 .. $n).pick;
Line 4,110: Line 4,110:
}
}
return @a;
return @a;
}</lang>
}</syntaxhighlight>
The shuffle is also built into the pick method on lists when you pass it a "whatever" for the number to pick:
The shuffle is also built into the pick method on lists when you pass it a "whatever" for the number to pick:
<lang perl6>my @deck = @cards.pick(*);</lang>
<syntaxhighlight lang="raku" line>my @deck = @cards.pick(*);</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Fisher-Yates"
Title: "Fisher-Yates"
Purpose: {Fisher-Yates shuffling algorithm}
Purpose: {Fisher-Yates shuffling algorithm}
Line 4,132: Line 4,132:
]
]
b
b
]</lang>
]</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===version 0, card pips===
===version 0, card pips===
<lang rexx>/*REXX program shuffles a deck of playing cards (with jokers) using the Knuth shuffle.*/
<syntaxhighlight 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. */
rank= 'A 2 3 4 5 6 7 8 9 10 J Q K' /*pips of the various playing cards. */
suit= '♣♠♦♥' /*suit " " " " " */
suit= '♣♠♦♥' /*suit " " " " " */
Line 4,158: Line 4,158:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: _=; do m=1 for cards; _=_ @.m; end /*m*/; say _; return</lang>
show: _=; do m=1 for cards; _=_ @.m; end /*m*/; say _; return</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 4,170: Line 4,170:
===version 1, card names===
===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.
This version handles items with (leading/trailing/embedded) blanks in them, so &nbsp; '''parse''' &nbsp; isn't an option for shuffling.
<lang rexx>/*REXX program shuffles a deck of playing cards (with jokers) using the Knuth shuffle.*/
<syntaxhighlight 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*/
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 " " " */
suit = 'club spade diamond heart' /* " suit " " " */
Line 4,196: Line 4,196:
say 'card' right(m, 2) '───►' @.m /*display a particular card from deck. */
say 'card' right(m, 2) '───►' @.m /*display a particular card from deck. */
end /*m*/
end /*m*/
return</lang>
return</syntaxhighlight>
'''output'''
'''output'''
<pre style="height:50ex">
<pre style="height:50ex">
Line 4,319: Line 4,319:


===version 2===
===version 2===
<lang rexx>/* REXX ---------------------------------------------------------------
<syntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 05.01.2014 Walter Pachl
* 05.01.2014 Walter Pachl
* borrow one improvement from version 1
* borrow one improvement from version 1
Line 4,341: Line 4,341:
Do k=1 To n; ol=ol right(a.k,2); End
Do k=1 To n; ol=ol right(a.k,2); End
Say ol
Say ol
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>In 1 2 3 4 5 6 7 8 9 10
<pre>In 1 2 3 4 5 6 7 8 9 10
Line 4,356: Line 4,356:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Knuth shuffle
# Project : Knuth shuffle


Line 4,385: Line 4,385:
see svect
see svect
see "]" + nl
see "]" + nl
</syntaxhighlight>
</lang>
<pre>
<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]
[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]
Line 4,392: Line 4,392:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|Tcl}}
{{trans|Tcl}}
<lang ruby>class Array
<syntaxhighlight lang="ruby">class Array
def knuth_shuffle!
def knuth_shuffle!
j = length
j = length
Line 4,412: Line 4,412:
end
end


r.keys.sort.each {|a| puts "#{a.inspect} => #{r[a]}"}</lang>
r.keys.sort.each {|a| puts "#{a.inspect} => #{r[a]}"}</syntaxhighlight>
results in
results in
<pre>[1, 2, 3] => 16572
<pre>[1, 2, 3] => 16572
Line 4,421: Line 4,421:
[3, 2, 1] => 16633</pre>
[3, 2, 1] => 16633</pre>
'''More idiomatic:'''
'''More idiomatic:'''
<lang ruby>class Array
<syntaxhighlight lang="ruby">class Array
def knuth_shuffle!
def knuth_shuffle!
(length - 1).downto(1) do |i|
(length - 1).downto(1) do |i|
Line 4,429: Line 4,429:
self
self
end
end
end</lang>
end</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>dim cards(52)
<syntaxhighlight lang="runbasic">dim cards(52)
for i = 1 to 52 ' make deck
for i = 1 to 52 ' make deck
cards(i) = i
cards(i) = i
Line 4,451: Line 4,451:
if i mod 18 = 0 then print
if i mod 18 = 0 then print
next
next
print</lang>
print</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|rand}}
{{libheader|rand}}
<lang rust>use rand::Rng;
<syntaxhighlight lang="rust">use rand::Rng;


extern crate rand;
extern crate rand;
Line 4,475: Line 4,475:
knuth_shuffle(&mut v);
knuth_shuffle(&mut v);
println!("after: {:?}", v);
println!("after: {:?}", v);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>def shuffle[T](a: Array[T]) = {
<syntaxhighlight lang="scala">def shuffle[T](a: Array[T]) = {
for (i <- 1 until a.size reverse) {
for (i <- 1 until a.size reverse) {
val j = util.Random nextInt (i + 1)
val j = util.Random nextInt (i + 1)
Line 4,486: Line 4,486:
}
}
a
a
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
A functional version, using lists (inefficient), somewhat unusual in reversing the entire initial sublist on each pass instead of just swapping:
A functional version, using lists (inefficient), somewhat unusual in reversing the entire initial sublist on each pass instead of just swapping:
<lang Scheme>#!r6rs
<syntaxhighlight lang="scheme">#!r6rs
(import (rnrs base (6))
(import (rnrs base (6))
(srfi :27 random-bits))
(srfi :27 random-bits))
Line 4,507: Line 4,507:
(let
(let
((li-prime (semireverse li (random-integer (length li)))))
((li-prime (semireverse li (random-integer (length li)))))
(cons (car li-prime) (shuffle (cdr li-prime))))))</lang>
(cons (car li-prime) (shuffle (cdr li-prime))))))</syntaxhighlight>


A mutable version, using vectors (efficient):
A mutable version, using vectors (efficient):
<lang Scheme>#!r6rs
<syntaxhighlight lang="scheme">#!r6rs
(import (rnrs base (6))
(import (rnrs base (6))
(srfi :27 random-bits))
(srfi :27 random-bits))
Line 4,531: Line 4,531:
((j (random-integer i)))
((j (random-integer i)))
(vector-swap! vec (- i 1) j)))
(vector-swap! vec (- i 1) j)))
(countdown (vector-length vec))))</lang>
(countdown (vector-length vec))))</syntaxhighlight>


=={{header|Scratch}}==
=={{header|Scratch}}==
Line 4,537: Line 4,537:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const type: intArray is array integer;
const type: intArray is array integer;
Line 4,568: Line 4,568:
end for;
end for;
writeln;
writeln;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,576: Line 4,576:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>set list to 1..9 -- a range, will become a list as needed
<syntaxhighlight lang="sensetalk">set list to 1..9 -- a range, will become a list as needed
set last to the number of items in list
set last to the number of items in list


Line 4,584: Line 4,584:
end repeat
end repeat


put list</lang>
put list</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,591: Line 4,591:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func knuth_shuffle(a) {
<syntaxhighlight lang="ruby">func knuth_shuffle(a) {
for i (a.len ^.. 1) {
for i (a.len ^.. 1) {
var j = i.irand
var j = i.irand
Line 4,599: Line 4,599:
}
}


say knuth_shuffle(@(1..10))</lang>
say knuth_shuffle(@(1..10))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,607: Line 4,607:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>"The selector swap:with: is documented, but it seems not
<syntaxhighlight 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"
implemented (GNU Smalltalk version 3.0.4); so here it is an implementation"
SequenceableCollection extend [
SequenceableCollection extend [
Line 4,628: Line 4,628:
]
]
]
]
].</lang>
].</syntaxhighlight>
Testing
Testing
<lang smalltalk>"Test"
<syntaxhighlight lang="smalltalk">"Test"
|c|
|c|
c := OrderedCollection new.
c := OrderedCollection new.
c addAll: #( 1 2 3 4 5 6 7 8 9 ).
c addAll: #( 1 2 3 4 5 6 7 8 9 ).
Shuffler Knuth: c.
Shuffler Knuth: c.
c display.</lang>
c display.</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang SNOBOL4>* Library for random()
<syntaxhighlight lang="snobol4">* Library for random()
-include 'Random.sno'
-include 'Random.sno'


Line 4,667: Line 4,667:
shuffle(a)
shuffle(a)
output = a2s(a)
output = a2s(a)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10 ->
<pre>1 2 3 4 5 6 7 8 9 10 ->
Line 4,674: Line 4,674:
=={{header|Stata}}==
=={{header|Stata}}==


<lang stata>mata
<syntaxhighlight lang="stata">mata
function shuffle(a) {
function shuffle(a) {
n = length(a)
n = length(a)
Line 4,688: Line 4,688:


shuffle(1..10)
shuffle(1..10)
end</lang>
end</syntaxhighlight>


'''Output'''
'''Output'''
Line 4,701: Line 4,701:
'''Simple version (any Swift version):''' Extend Array with shuffle methods; using arc4random_uniform from C stdlib:
'''Simple version (any Swift version):''' Extend Array with shuffle methods; using arc4random_uniform from C stdlib:


<lang swift>import func Darwin.arc4random_uniform
<syntaxhighlight lang="swift">import func Darwin.arc4random_uniform


extension Array {
extension Array {
Line 4,720: Line 4,720:
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())
// Swift 1.x:
// Swift 1.x:
//println([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())</lang>
//println([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())</syntaxhighlight>


{{out}}
{{out}}
Line 4,727: Line 4,727:
'''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:
'''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:


<lang swift>import func Darwin.arc4random_uniform
<syntaxhighlight lang="swift">import func Darwin.arc4random_uniform


func shuffleInPlace<T: MutableCollectionType where T.Index: RandomAccessIndexType>(inout collection: T) {
func shuffleInPlace<T: MutableCollectionType where T.Index: RandomAccessIndexType>(inout collection: T) {
Line 4,757: Line 4,757:
print(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
// Swift 1.x:
// Swift 1.x:
//println(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))</lang>
//println(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))</syntaxhighlight>


{{out}}
{{out}}
Line 4,764: Line 4,764:
{{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:
{{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:


<lang swift>import func Darwin.arc4random_uniform
<syntaxhighlight lang="swift">import func Darwin.arc4random_uniform


// Define a protocol for shuffling:
// Define a protocol for shuffling:
Line 4,813: Line 4,813:
{ /* Implementation provided by Shufflable protocol extension */ }
{ /* Implementation provided by Shufflable protocol extension */ }


print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())</lang>
print([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle())</syntaxhighlight>


{{out}}
{{out}}
Line 4,819: Line 4,819:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc knuth_shuffle lst {
<syntaxhighlight lang="tcl">proc knuth_shuffle lst {
set j [llength $lst]
set j [llength $lst]
for {set i 0} {$j > 1} {incr i;incr j -1} {
for {set i 0} {$j > 1} {incr i;incr j -1} {
Line 4,835: Line 4,835:
5 2 1 4 3
5 2 1 4 3
% knuth_shuffle {tom dick harry peter paul mary}
% knuth_shuffle {tom dick harry peter paul mary}
tom paul mary harry peter dick</lang>
tom paul mary harry peter dick</syntaxhighlight>
As a test of skewing (an indicator of a poor implementation) this code was used:
As a test of skewing (an indicator of a poor implementation) this code was used:
<lang tcl>% for {set i 0} {$i<100000} {incr i} {
<syntaxhighlight 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} {
foreach val [knuth_shuffle {1 2 3 4 5}] pos {pos0 pos1 pos2 pos3 pos4} {
incr tots($pos) $val
incr tots($pos) $val
Line 4,847: Line 4,847:
tots(pos2) = 299701
tots(pos2) = 299701
tots(pos3) = 299830
tots(pos3) = 299830
tots(pos4) = 300240</lang>
tots(pos4) = 300240</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 4,868: Line 4,868:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
oldnumbers=newnumbers="",range=20
oldnumbers=newnumbers="",range=20
LOOP nr=1,#range
LOOP nr=1,#range
Line 4,882: Line 4,882:
ENDLOOP
ENDLOOP


PRINT "after ",newnumbers</lang>
PRINT "after ",newnumbers</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,890: Line 4,890:


=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
<lang>PRINT "before:"
<syntaxhighlight lang="text">PRINT "before:"
FOR L = 0 TO 51
FOR L = 0 TO 51
@(L) = L
@(L) = L
Line 4,911: Line 4,911:
END
END


100 @(POP()) = POP() : @(POP()) = POP() : RETURN</lang>
100 @(POP()) = POP() : @(POP()) = POP() : RETURN</syntaxhighlight>
{{out}}
{{out}}
<pre>before:
<pre>before:
Line 4,921: Line 4,921:
{{works with|ksh93}}
{{works with|ksh93}}
{{works with|pdksh}}
{{works with|pdksh}}
<lang bash># Shuffle array[@].
<syntaxhighlight lang="bash"># Shuffle array[@].
function shuffle {
function shuffle {
integer i j t
integer i j t
Line 4,941: Line 4,941:
set -A array 11 22 33 44 55 66 77 88 99 110
set -A array 11 22 33 44 55 66 77 88 99 110
shuffle
shuffle
echo "${array[@]}"</lang>
echo "${array[@]}"</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
This function works on lists of any type and length, including character strings.
This function works on lists of any type and length, including character strings.
<lang Ursala>shuffle = @iNX ~&l->r ^jrX/~&l ~&lK8PrC</lang>
<syntaxhighlight lang="ursala">shuffle = @iNX ~&l->r ^jrX/~&l ~&lK8PrC</syntaxhighlight>
test program:
test program:
<lang Ursala>#cast %s
<syntaxhighlight lang="ursala">#cast %s


example = shuffle 'abcdefghijkl'</lang>
example = shuffle 'abcdefghijkl'</syntaxhighlight>
{{out}}
{{out}}
<pre>'keacfjlbdigh'</pre>
<pre>'keacfjlbdigh'</pre>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Private Sub Knuth(Optional ByRef a As Variant)
<syntaxhighlight lang="vb">Private Sub Knuth(Optional ByRef a As Variant)
Dim t As Variant, i As Integer
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
If Not IsMissing(a) Then
Line 5,002: Line 5,002:
Debug.Print "After: ";
Debug.Print "After: ";
For Each i In f: Debug.Print i;: Next i: Debug.Print
For Each i In f: Debug.Print i;: Next i: Debug.Print
End Sub</lang>{{out}}<pre>Before:
End Sub</syntaxhighlight>{{out}}<pre>Before:
After:
After:
Before: 10
Before: 10
Line 5,018: Line 5,018:
=={{header|VBScript}}==
=={{header|VBScript}}==
;Implementation
;Implementation
<syntaxhighlight lang="vb">
<lang vb>
function shuffle( a )
function shuffle( a )
dim i
dim i
Line 5,037: Line 5,037:
a = b
a = b
b = tmp
b = tmp
end sub</lang>
end sub</syntaxhighlight>
;Invocation
;Invocation
<lang vb>dim a
<syntaxhighlight lang="vb">dim a
a = array( 1,2,3,4,5,6,7,8,9)
a = array( 1,2,3,4,5,6,7,8,9)
wscript.echo "before: ", join( a, ", " )
wscript.echo "before: ", join( a, ", " )
Line 5,052: Line 5,052:
wscript.echo "after: ", join( a, ", " )
wscript.echo "after: ", join( a, ", " )
shuffle a
shuffle a
wscript.echo "after: ", join( a, ", " )</lang>
wscript.echo "after: ", join( a, ", " )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,069: Line 5,069:


The output will be inserted in current edit buffer.
The output will be inserted in current edit buffer.
<lang vedit>// Test main
<syntaxhighlight lang="vedit">// Test main
#90 = Time_Tick // seed for random number generator
#90 = Time_Tick // seed for random number generator
#99 = 20 // number of items in the array
#99 = 20 // number of items in the array
Line 5,110: Line 5,110:
#93 = 0x7fffffff % 48271
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)</lang>
Return ((#90 & 0xffff) * #91 / 0x10000)</syntaxhighlight>
{{out}}
{{out}}
<pre>Before:
<pre>Before:
Line 5,119: Line 5,119:
=={{header|Vlang}}==
=={{header|Vlang}}==
Updated to Vlang version 0.2.2
Updated to Vlang version 0.2.2
<lang go>import rand
<syntaxhighlight lang="go">import rand
import rand.seed
import rand.seed


Line 5,139: Line 5,139:
println('Output: $arr')
println('Output: $arr')
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Input: [6, 9, 1, 4]
<pre>Input: [6, 9, 1, 4]
Line 5,147: Line 5,147:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random


var rand = Random.new()
var rand = Random.new()
Line 5,167: Line 5,167:
knuthShuffle.call(a)
knuthShuffle.call(a)
System.print("%(b) -> %(a)")
System.print("%(b) -> %(a)")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,179: Line 5,179:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>proc Shuffle(Array, Items, BytesPerItem);
<syntaxhighlight lang="xpl0">proc Shuffle(Array, Items, BytesPerItem);
int Array, Items, BytesPerItem;
int Array, Items, BytesPerItem;
int I, J;
int I, J;
Line 5,214: Line 5,214:
[IntOut(0, A(I)); ChOut(0, ^ )];
[IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 5,225: Line 5,225:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang yabasic>// Rosetta Code problem: https://www.rosettacode.org/wiki/Ramsey%27s_theorem
<syntaxhighlight lang="yabasic">// Rosetta Code problem: https://www.rosettacode.org/wiki/Ramsey%27s_theorem
// by Jjuanhdez, 06/2022
// by Jjuanhdez, 06/2022


Line 5,256: Line 5,256:
a(lb + j) = t
a(lb + j) = t
next i
next i
end sub</lang>
end sub</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Two versions, imperative and functional, same results.
Two versions, imperative and functional, same results.
xs has to be a mutable list.
xs has to be a mutable list.
<lang zkl>fcn kshuffle(xs){
<syntaxhighlight lang="zkl">fcn kshuffle(xs){
foreach i in ([xs.len()-1..1,-1]){ xs.swap(i,(0).random(0,i+1)) }
foreach i in ([xs.len()-1..1,-1]){ xs.swap(i,(0).random(0,i+1)) }
xs
xs
Line 5,268: Line 5,268:
[xs.len()-1..1,-1].pump(Void,'wrap(i){ xs.swap(i,(0).random(0,i+1)) })
[xs.len()-1..1,-1].pump(Void,'wrap(i){ xs.swap(i,(0).random(0,i+1)) })
xs
xs
}</lang>
}</syntaxhighlight>
<pre>
<pre>
var ns=(1).pump(10,List).copy() // [1..10] made mutable
var ns=(1).pump(10,List).copy() // [1..10] made mutable