Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Knuth_shuffle
note: Classic CS problems and programs

View file

@ -0,0 +1,49 @@
The   [[wp:Knuth shuffle|Knuth shuffle]]   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array.
;Task:
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
;Specification:
Given an array '''''items''''' with indices ranging from ''0'' to '''''last''''', the algorithm can be defined as follows (pseudo-code):
'''for''' ''i'' '''from''' ''last'' '''downto''' 1 '''do''':
'''let''' ''j'' = random integer in range ''0'' <math>\leq</math> ''j'' <math>\leq</math> ''i''
'''swap''' ''items''[''i''] '''with''' ''items''[''j'']
;Notes:
* &nbsp; It modifies the input array in-place.
* &nbsp; If that is unreasonable in your programming language, you may amend the algorithm to return the shuffled items as a new array instead.
* &nbsp; The algorithm can also be amended to iterate from left to right, if that is more convenient.
;Test cases:
::::::{| class="wikitable"
|-
! Input array
! Possible output arrays
|-
| <tt>[]</tt>
| <tt>[]</tt>
|-
| <tt>[10]</tt>
| <tt>[10]</tt>
|-
| <tt>[10, 20]</tt>
| <tt>[10, 20]</tt><br><tt>[20, 10]</tt>
|-
| <tt>[10, 20, 30]</tt>
| <tt>[10, 20, 30]</tt><br><tt>[10, 30, 20]</tt><br><tt>[20, 10, 30]</tt><br><tt>[20, 30, 10]</tt><br><tt>[30, 10, 20]</tt><br><tt>[30, 20, 10]</tt>
|}
(These are listed here just for your convenience; no need to demonstrate them on the page.)
;Related task:
* [[Sattolo cycle]]
{{Template:Strings}}
<br><br>

View file

@ -0,0 +1,8 @@
F knuth_shuffle(&x)
L(i) (x.len - 1 .< 0).step(-1)
V j = random:(0..i)
swap(&x[i], &x[j])
V x = Array(0..9)
knuth_shuffle(&x)
print(shuffled: x)

View file

@ -0,0 +1,49 @@
* Knuth shuffle 02/11/2015
KNUTHSH CSECT
USING KNUTHSH,R15
LA R6,1 i=1
LOOPI1 C R6,=A(CARDS) do i=1 to cards
BH ELOOPI1
STC R6,PACK(R6) pack(i)=i
LA R6,1(R6) i=i+1
B LOOPI1
ELOOPI1 LA R7,CARDS n=cards
LOOPN C R7,=F'2' do n=cards to 2 by -1
BL ELOOPN
L R5,RANDSEED r5=seed
M R4,=F'397204094' r4r5=seed*const
D R4,=X'7FFFFFFF' r5=r5 div (2^31-1)
ST R4,RANDSEED r4=r5 mod (2^31-1); seed=r4
LR R5,R4 r5=seed
LA R4,0 r4=0
DR R4,R7 r5=seed div n; r4=seed mod n
LA R9,1(R4) r2=randint(n)+1 [1:n]
LA R4,PACK(R7) @pack(n)
LA R5,PACK(R9) @pack(nw)
MVC TMP,0(R4) tmp=pack(n)
MVC 0(1,R4),0(R5) pack(n)=pack(nw)
MVC 0(1,R5),TMP pack(nw)=tmp
BCTR R7,0 n=n-1
B LOOPN
ELOOPN LA R6,1 i=1
LA R8,PG pgi=@pg
LOOPI2 C R6,=A(CARDS) do i=1 to cards
BH ELOOPI2
XR R2,R2 r2=0
IC R2,PACK(R6) pack(i)
XDECO R2,XD edit pack(i)
MVC 0(3,R8),XD+9 output pack(i)
LA R8,3(R8) pgi=pgi+3
LA R6,1(R6) i=i+1
B LOOPI2
ELOOPI2 XPRNT PG,80 print buffer
XR R15,R15 set return code
BR R14 return to caller
CARDS EQU 20 number of cards
PACK DS (CARDS+1)C pack of cards
TMP DS C temp for swap
PG DC CL80' ' buffer
XD DS CL12 to decimal
RANDSEED DC F'16807' running seed
YREGS
END KNUTHSH

View file

@ -0,0 +1,69 @@
define sysRandom $fe
define tempMask $ff
define range $00
define tempX $01
define tempY $02
define tempRandIndex $03
define temp $04
CreateIdentityTable:
txa
sta $0200,x
sta $1000,x
inx
bne CreateIdentityTable
;creates a sorted array from 0-255 starting at addr $1000
;also creates another one at $0200 for our test input
lda #1
sta range
ConstrainRNG:
ldx #255
;max range of RNG
lda range
bne outerloop
jmp end
outerloop:
cpx range
bcc continue ;if X >= range, we need to lower X
pha
txa
sta tempX
lsr
cmp range
bcc continue2
tax
pla
jmp outerloop
continue2:
pla
ldx tempX
continue:
ldy range
KnuthShuffle:
lda sysRandom
and $1000,x ;and with range constrictor
tay
lda $0200,y
sty tempRandIndex
sta temp
ldy range
lda $0200,y
pha
lda temp
sta $0200,y
pla
ldy tempRandIndex
sta $0200,y
dec range
jmp ConstrainRNG
end:
brk

View file

@ -0,0 +1,141 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program knuthshuffle64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .quad 1,2,3,4,5,6,7,8,9,10
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConversion: .skip 30
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl knuthShuffle
ldr x2,qAdrTableNumber
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConversion // display value
bl conversion10S // call function
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConversion
bl strInsertAtCharInc
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
/* 2e shuffle */
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl knuthShuffle
ldr x2,qAdrTableNumber
mov x3,0
2: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConversion // display value
bl conversion10S // call function
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConversion
bl strInsertAtCharInc
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 2b
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrsZoneConversion: .quad sZoneConversion
/******************************************************************/
/* Knuth Shuffle */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements */
knuthShuffle:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x5,x0 // save table address
mov x6,x1 // save number of elements
mov x2,0 // start index
1:
mov x0,0
mov x1,x2 // generate aleas
bl extRandom
ldr x3,[x5,x2,lsl 3] // swap number on the table
ldr x4,[x5,x0,lsl 3]
str x4,[x5,x2,lsl 3]
str x3,[x5,x0,lsl 3]
add x2,x2,1 // next number
cmp x2,x6 // end ?
blt 1b // no -> loop
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret
/******************************************************************/
/* random number */
/******************************************************************/
/* x0 contains inferior value */
/* x1 contains maxi value */
/* x0 return random number */
extRandom:
stp x1,lr,[sp,-16]! // save registers
stp x2,x8,[sp,-16]! // save registers
stp x19,x20,[sp,-16]! // save registers
sub sp,sp,16 // reserve 16 octets on stack
mov x19,x0
add x20,x1,1
mov x0,sp // store result on stack
mov x1,8 // length 8 bytes
mov x2,0
mov x8,278 // call system Linux 64 bits Urandom
svc 0
mov x0,sp // load résult on stack
ldr x0,[x0]
sub x2,x20,x19 // calculation of the range of values
udiv x1,x0,x2 // calculation range modulo
msub x0,x1,x2,x0
add x0,x0,x19 // and add inferior value
100:
add sp,sp,16 // alignement stack
ldp x19,x20,[sp],16 // restaur 2 registers
ldp x2,x8,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

View file

@ -0,0 +1,24 @@
:set-state-ok t
(defun array-swap (name array i j)
(let ((ai (aref1 name array i))
(aj (aref1 name array j)))
(aset1 name
(aset1 name array j ai)
i aj)))
(defun shuffle-r (name array m state)
(if (zp m)
(mv array state)
(mv-let (i state)
(random$ m state)
(shuffle-r name
(array-swap name array i m)
(1- m)
state))))
(defun shuffle (name array state)
(shuffle-r name
array
(1- (first (dimensions name array)))
state))

View file

@ -0,0 +1,14 @@
PROC between = (INT a, b)INT :
(
ENTIER (random * ABS (b-a+1) + (a<b|a|b))
);
PROC knuth shuffle = (REF[]INT a)VOID:
(
FOR i FROM LWB a TO UPB a DO
INT j = between(LWB a, UPB a);
INT t = a[i];
a[i] := a[j];
a[j] := t
OD
);

View file

@ -0,0 +1,6 @@
main:(
[20]INT a;
FOR i FROM 1 TO 20 DO a[i] := i OD;
knuth shuffle(a);
print(a)
)

View file

@ -0,0 +1,229 @@
/* ARM assembly Raspberry PI */
/* program knuthShuffle.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii "Value : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
.align 4
iGraine: .int 123456
.equ NBELEMENTS, 10
TableNumber: .int 1,2,3,4,5,6,7,8,9,10
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl knuthShuffle
ldr r2,iAdrTableNumber
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
/* 2e shuffle */
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl knuthShuffle
ldr r2,iAdrTableNumber
mov r3,#0
2: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 2b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
/******************************************************************/
/* Knuth Shuffle */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements */
knuthShuffle:
push {r2-r5,lr} @ save registers
mov r5,r0 @ save table address
mov r2,#0 @ start index
1:
mov r0,r2 @ generate aleas
bl genereraleas
ldr r3,[r5,r2,lsl #2] @ swap number on the table
ldr r4,[r5,r0,lsl #2]
str r4,[r5,r2,lsl #2]
str r3,[r5,r0,lsl #2]
add r2,#1 @ next number
cmp r2,r1 @ end ?
blt 1b @ no -> loop
100:
pop {r2-r5,lr}
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
/***************************************************/
/* Generation random number */
/***************************************************/
/* r0 contains limit */
genereraleas:
push {r1-r4,lr} @ save registers
ldr r4,iAdriGraine
ldr r2,[r4]
ldr r3,iNbDep1
mul r2,r3,r2
ldr r3,iNbDep1
add r2,r2,r3
str r2,[r4] @ maj de la graine pour l appel suivant
cmp r0,#0
beq 100f
mov r1,r0 @ divisor
mov r0,r2 @ dividende
bl division
mov r0,r3 @ résult = remainder
100: @ end function
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/*****************************************************/
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* integer division unsigned */
/***************************************************/
division:
/* r0 contains dividend */
/* r1 contains divisor */
/* r2 returns quotient */
/* r3 returns remainder */
push {r4, lr}
mov r2, #0 @ init quotient
mov r3, #0 @ init remainder
mov r4, #32 @ init counter bits
b 2f
1: @ loop
movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
cmp r3, r1 @ compute r3 - r1 and update cpsr
subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1
adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
subs r4, r4, #1 @ r4 <- r4 - 1
bpl 1b @ if r4 >= 0 (N=0) then loop
pop {r4, lr}
bx lr

View file

@ -0,0 +1,21 @@
# Shuffle an _array_ with indexes from 1 to _len_.
function shuffle(array, len, i, j, t) {
for (i = len; i > 1; i--) {
# j = random integer from 1 to i
j = int(i * rand()) + 1
# swap array[i], array[j]
t = array[i]
array[i] = array[j]
array[j] = t
}
}
# Test program.
BEGIN {
len = split("11 22 33 44 55 66 77 88 99 110", array)
shuffle(array, len)
for (i = 1; i < len; i++) printf "%s ", array[i]
printf "%s\n", array[len]
}

View file

@ -0,0 +1,43 @@
PROC PrintTable(INT ARRAY tab BYTE size)
BYTE i
FOR i=0 TO size-1
DO
PrintF("%I ",tab(i))
OD
PutE()
RETURN
PROC KnuthShuffle(INT ARRAY tab BYTE size)
BYTE i,j
INT tmp
i=size-1
WHILE i>0
DO
j=Rand(i+1)
tmp=tab(i)
tab(i)=tab(j)
tab(j)=tmp
i==-1
OD
RETURN
PROC Main()
BYTE i,size=[20]
INT ARRAY tab(size)
FOR i=0 TO size-1
DO
tab(i)=-50+10*i
OD
PrintE("Original data:")
PrintTable(tab,size)
PutE()
KnuthShuffle(tab,size)
PrintE("Shuffled data:")
PrintTable(tab,size)
RETURN

View file

@ -0,0 +1,5 @@
generic
type Element_Type is private;
type Array_Type is array (Positive range <>) of Element_Type;
procedure Generic_Shuffle (List : in out Array_Type);

View file

@ -0,0 +1,17 @@
with Ada.Numerics.Discrete_Random;
procedure Generic_Shuffle (List : in out Array_Type) is
package Discrete_Random is new Ada.Numerics.Discrete_Random(Result_Subtype => Integer);
use Discrete_Random;
K : Integer;
G : Generator;
T : Element_Type;
begin
Reset (G);
for I in reverse List'Range loop
K := (Random(G) mod I) + 1;
T := List(I);
List(I) := List(K);
List(K) := T;
end loop;
end Generic_Shuffle;

View file

@ -0,0 +1,22 @@
with Ada.Text_IO;
with Generic_Shuffle;
procedure Test_Shuffle is
type Integer_Array is array (Positive range <>) of Integer;
Integer_List : Integer_Array
:= (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18);
procedure Integer_Shuffle is new Generic_Shuffle(Element_Type => Integer,
Array_Type => Integer_Array);
begin
for I in Integer_List'Range loop
Ada.Text_IO.Put(Integer'Image(Integer_List(I)));
end loop;
Integer_Shuffle(List => Integer_List);
Ada.Text_IO.New_Line;
for I in Integer_List'Range loop
Ada.Text_IO.Put(Integer'Image(Integer_List(I)));
end loop;
end Test_Shuffle;

View file

@ -0,0 +1,14 @@
void
shuffle(list l)
{
integer i;
i = ~l;
if (i) {
i -= 1;
while (i) {
l.spin(i, drand(i));
i -= 1;
}
}
}

View file

@ -0,0 +1,14 @@
set n to 25
set array to {}
repeat with i from 1 to n
set end of array to i
end repeat
copy {array, array} to {unshuffled, shuffled}
repeat with i from n to 1 by -1
set j to (((random number) * (i - 1)) as integer) + 1
set shuffled's item i to array's item j
if j i's contents then set array's item j to array's item i
end repeat
return {unshuffled, shuffled}

View file

@ -0,0 +1,2 @@
{{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}}

View file

@ -0,0 +1,25 @@
-- Fisher-Yates (aka Durstenfeld, aka Knuth) shuffle.
on shuffle(theList, l, r)
set listLength to (count theList)
if (listLength < 2) then return array
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
end script
repeat with i from l to (r - 1)
set j to (random number from i to r)
set v to o's lst's item i
set o's lst's item i to o's lst's item j
set o's lst's item j to v
end repeat
return theList
end shuffle
local array
set array to {"Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike"}
-- Shuffle all items (1 thru -1).
shuffle(array, 1, -1)

View file

@ -0,0 +1 @@
{"Golf", "Foxtrot", "Echo", "Delta", "Kilo", "Charlie", "Mike", "Alpha", "Lima", "Juliett", "India", "Bravo", "Hotel"}

View file

@ -0,0 +1,24 @@
use AppleScript version "2.5" -- OS X 10.11 (El Capitan) or later
use framework "Foundation"
use framework "GameplayKit"
on shuffle(theList, l, r)
set listLength to (count theList)
if (listLength < 2) then return theList
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
end script
set rndGenerator to current application's class "GKRandomDistribution"'s distributionWithLowestValue:(l) highestValue:(r)
repeat with i from r to (l + 1) by -1
set j to (rndGenerator's nextIntWithUpperBound:(i))
set v to o's lst's item i
set o's lst's item i to o's lst's item j
set o's lst's item j to v
end repeat
return theList
end shuffle

View file

@ -0,0 +1,72 @@
-- KNUTH SHUFFLE -------------------------------------------------------------
-- knuthShuffle :: [a] -> [a]
on knuthShuffle(xs)
-- randomSwap :: [Int] -> Int -> [Int]
script randomSwap
on |λ|(a, i)
if i > 1 then
set iRand to random number from 1 to i
tell a
set tmp to item iRand
set item iRand to item i
set item i to tmp
it
end tell
else
a
end if
end |λ|
end script
foldr(randomSwap, xs, enumFromTo(1, length of xs))
end knuthShuffle
-- TEST ----------------------------------------------------------------------
on run
knuthShuffle(["alpha", "beta", "gamma", "delta", "epsilon", ¬
"zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"])
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

View file

@ -0,0 +1,2 @@
{"mu", "theta", "alpha", "delta", "zeta", "gamma",
"iota", "kappa", "lambda", "epsilon", "beta", "eta"}

View file

@ -0,0 +1,13 @@
100 :
110 REM KNUTH SHUFFLE
120 :
130 DIM A(25)
140 FOR I = 1 TO 25
150 A(I) = I: PRINT A(I);" ";: NEXT I
160 PRINT : PRINT
170 FOR I = 25 TO 2 STEP - 1
180 J = INT ( RND (1) * I + 1)
190 T = A(I):A(I) = A(J):A(J) = T: NEXT I
200 FOR I = 1 TO 25
210 PRINT A(I);" ";: NEXT I
220 END

View file

@ -0,0 +1,18 @@
knuth: function [arr][
if 0=size arr -> return []
loop ((size arr)-1)..0 'i [
j: random 0 i
tmp: arr\[i]
set arr i arr\[j]
set arr j tmp
]
return arr
]
print knuth []
print knuth [10]
print knuth [10 20]
print knuth [10 20 30]

View file

@ -0,0 +1,13 @@
MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
MsgBox % shuffle("1,2,3,4,5,6,7,8,9")
shuffle(list) { ; shuffle comma separated list, converted to array
StringSplit a, list, `, ; make array (length = a0)
Loop % a0-1 {
Random i, A_Index, a0 ; swap item 1,2... with a random item to the right of it
t := a%i%, a%i% := a%A_Index%, a%A_Index% := t
}
Loop % a0 ; construct string from sorted array
s .= "," . a%A_Index%
Return SubStr(s,2) ; drop leading comma
}

View file

@ -0,0 +1,17 @@
toShuffle:=[1,2,3,4,5,6]
shuffled:=shuffle(toShuffle)
;p(toShuffle) ;because it modifies the original array
;or
;p(shuffled)
shuffle(a)
{
i := a.Length()
loop % i-1 {
Random, j,1,% i
x := a[i]
a[i] := a[j]
a[j] := x
i--
}
return a
}

View file

@ -0,0 +1,25 @@
Dim $a[10]
ConsoleWrite('array before permutation:' & @CRLF)
For $i = 0 To 9
$a[$i] = Random(20,100,1)
ConsoleWrite($a[$i] & ' ')
Next
ConsoleWrite(@CRLF)
_Permute($a)
ConsoleWrite('array after permutation:' & @CRLF)
For $i = 0 To UBound($a) -1
ConsoleWrite($a[$i] & ' ')
Next
ConsoleWrite(@CRLF)
Func _Permute(ByRef $array)
Local $random, $tmp
For $i = UBound($array) -1 To 0 Step -1
$random = Random(0,$i,1)
$tmp = $array[$random]
$array[$random] = $array[$i]
$array[$i] = $tmp
Next
EndFunc

View file

@ -0,0 +1,21 @@
RANDOMIZE TIMER
DIM cards(51) AS INTEGER
DIM L0 AS LONG, card AS LONG
PRINT "before:"
FOR L0 = 0 TO 51
cards(L0) = L0
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT
FOR L0 = 51 TO 0 STEP -1
card = INT(RND * (L0 + 1))
IF card <> L0 THEN SWAP cards(card), cards(L0)
NEXT
PRINT : PRINT "after:"
FOR L0 = 0 TO 51
PRINT LTRIM$(STR$(cards(L0))); " ";
NEXT
PRINT

View file

@ -0,0 +1,12 @@
cards% = 52
DIM pack%(cards%)
FOR I% = 1 TO cards%
pack%(I%) = I%
NEXT I%
FOR N% = cards% TO 2 STEP -1
SWAP pack%(N%),pack%(RND(N%))
NEXT N%
FOR I% = 1 TO cards%
PRINT pack%(I%);
NEXT I%
PRINT

View file

@ -0,0 +1,14 @@
Knuth {
𝕊 arr:
l arr
{
arr (•rand.Range l, 𝕩)arr
}¨l
arr
}
P •Show Knuth
P
P 10
P 10, 20
P 10, 20, 30

View file

@ -0,0 +1,44 @@
seed = 1 /* seed of the random number generator */
scale = 0
/* Random number from 0 to 32767. */
define rand() {
/* Formula (from POSIX) for random numbers of low quality. */
seed = (seed * 1103515245 + 12345) % 4294967296
return ((seed / 65536) % 32768)
}
/* Shuffle the first _count_ elements of shuffle[]. */
define shuffle(count) {
auto b, i, j, t
i = count
while (i > 0) {
/* j = random number in [0, i) */
b = 32768 % i /* want rand() >= b */
while (1) {
j = rand()
if (j >= b) break
}
j = j % i
/* decrement i, swap shuffle[i] and shuffle[j] */
t = shuffle[--i]
shuffle[i] = shuffle[j]
shuffle[j] = t
}
}
/* Test program. */
define print_array(count) {
auto i
for (i = 0; i < count - 1; i++) print shuffle[i], ", "
print shuffle[i], "\n"
}
for (i = 0; i < 10; i++) shuffle[i] = 11 * (i + 1)
"Original array: "; trash = print_array(10)
trash = shuffle(10)
"Shuffled array: "; trash = print_array(10)
quit

View file

@ -0,0 +1,12 @@
shuffle = { a |
(a.length - 1).to 1 { i |
random_index = random(0, i)
temp = a[i]
a[i] = a[random_index]
a[random_index] = temp
}
a
}
p shuffle [1 2 3 4 5 6 7]

View file

@ -0,0 +1,13 @@
#include <cstdlib>
#include <algorithm>
#include <iterator>
template<typename RandomAccessIterator>
void knuthShuffle(RandomAccessIterator begin, RandomAccessIterator end) {
for(unsigned int n = end - begin - 1; n >= 1; --n) {
unsigned int k = rand() % (n + 1);
if(k != n) {
std::iter_swap(begin + k, begin + n);
}
}
}

View file

@ -0,0 +1,11 @@
#include <algorithm>
#include <vector>
int main()
{
int array[] = { 1,2,3,4,5,6,7,8,9 }; // C-style array of integers
std::vector<int> vec(array, array + 9); // build STL container from int array
std::random_shuffle(array, array + 9); // shuffle C-style array
std::random_shuffle(vec.begin(), vec.end()); // shuffle STL container
}

View file

@ -0,0 +1,9 @@
public static void KnuthShuffle<T>(T[] array)
{
System.Random random = new System.Random();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(i, array.Length); // Don't select from the entire array on subsequent loops
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}

View file

@ -0,0 +1,21 @@
#include <stdlib.h>
#include <string.h>
int rrand(int m)
{
return (int)((double)m * ( rand() / (RAND_MAX+1.0) ));
}
#define BYTE(X) ((unsigned char *)(X))
void shuffle(void *obj, size_t nmemb, size_t size)
{
void *temp = malloc(size);
size_t n = nmemb;
while ( n > 1 ) {
size_t k = rrand(n--);
memcpy(temp, BYTE(obj) + n*size, size);
memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size);
memcpy(BYTE(obj) + k*size, temp, size);
}
free(temp);
}

View file

@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
/* define a shuffle function. e.g. decl_shuffle(double).
* advantage: compiler is free to optimize the swap operation without
* indirection with pointers, which could be much faster.
* disadvantage: each datatype needs a separate instance of the function.
* for a small funciton like this, it's not very big a deal.
*/
#define decl_shuffle(type) \
void shuffle_##type(type *list, size_t len) { \
int j; \
type tmp; \
while(len) { \
j = irand(len); \
if (j != len - 1) { \
tmp = list[j]; \
list[j] = list[len - 1]; \
list[len - 1] = tmp; \
} \
len--; \
} \
} \
/* random integer from 0 to n-1 */
int irand(int n)
{
int r, rand_max = RAND_MAX - (RAND_MAX % n);
/* reroll until r falls in a range that can be evenly
* distributed in n bins. Unless n is comparable to
* to RAND_MAX, it's not *that* important really. */
while ((r = rand()) >= rand_max);
return r / (rand_max / n);
}
/* declare and define int type shuffle function from macro */
decl_shuffle(int);
int main()
{
int i, x[20];
for (i = 0; i < 20; i++) x[i] = i;
for (printf("before:"), i = 0; i < 20 || !printf("\n"); i++)
printf(" %d", x[i]);
shuffle_int(x, 20);
for (printf("after: "), i = 0; i < 20 || !printf("\n"); i++)
printf(" %d", x[i]);
return 0;
}

View file

@ -0,0 +1,21 @@
knuth_shuffle = proc [T: type] (a: array[T])
lo: int := array[T]$low(a)
hi: int := array[T]$high(a)
for i: int in int$from_to_by(hi, lo+1, -1) do
j: int := lo + random$next(i-lo+1)
temp: T := a[i]
a[i] := a[j]
a[j] := temp
end
end knuth_shuffle
start_up = proc ()
po: stream := stream$primary_output()
d: date := now()
random$seed(d.second + 60*(d.minute + 60*d.hour))
arr: array[int] := array[int]$[1,2,3,4,5,6,7,8,9]
knuth_shuffle[int](arr)
for i: int in array[int]$elements(arr) do
stream$puts(po, int$unparse(i) || " ")
end
end start_up

View file

@ -0,0 +1,33 @@
# shuffle(<output variable> [<value>...]) shuffles the values, and
# stores the result in a list.
function(shuffle var)
set(forever 1)
# Receive ARGV1, ARGV2, ..., ARGV${last} as an array of values.
math(EXPR last "${ARGC} - 1")
# Shuffle the array with Knuth shuffle (Fisher-Yates shuffle).
foreach(i RANGE ${last} 1)
# Roll j = a random number from 1 to i.
math(EXPR min "100000000 % ${i}")
while(forever)
string(RANDOM LENGTH 8 ALPHABET 0123456789 j)
if(NOT j LESS min) # Prevent modulo bias when j < min.
break() # Break loop when j >= min.
endif()
endwhile()
math(EXPR j "${j} % ${i} + 1")
# Swap ARGV${i} with ARGV${j}.
set(t ${ARGV${i}})
set(ARGV${i} ${ARGV${j}})
set(ARGV${j} ${t})
endforeach(i)
# Convert array to list.
set(answer)
foreach(i RANGE 1 ${last})
list(APPEND answer ${ARGV${i}})
endforeach(i)
set("${var}" ${answer} PARENT_SCOPE)
endfunction(shuffle)

View file

@ -0,0 +1,4 @@
shuffle(result 11 22 33 44 55 66)
message(STATUS "${result}")
# One possible output:
# -- 66;33;22;55;44;11

View file

@ -0,0 +1,29 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. knuth-shuffle.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PIC 9(8).
01 j PIC 9(8).
01 temp PIC 9(8).
LINKAGE SECTION.
78 Table-Len VALUE 10.
01 ttable-area.
03 ttable PIC 9(8) OCCURS Table-Len TIMES.
PROCEDURE DIVISION USING ttable-area.
MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (11:6)) TO i
PERFORM VARYING i FROM Table-Len BY -1 UNTIL i = 0
COMPUTE j =
FUNCTION MOD(FUNCTION RANDOM * 10000, Table-Len) + 1
MOVE ttable (i) TO temp
MOVE ttable (j) TO ttable (i)
MOVE temp TO ttable (j)
END-PERFORM
GOBACK
.

View file

@ -0,0 +1,4 @@
(defn shuffle [vect]
(reduce (fn [v i] (let [r (rand-int i)]
(assoc v i (v r) r (v i))))
vect (range (dec (count vect)) 1 -1)))

View file

@ -0,0 +1,21 @@
knuth_shuffle = (a) ->
n = a.length
while n > 1
r = Math.floor(n * Math.random())
n -= 1
[a[n], a[r]] = [a[r], a[n]]
a
counts =
"1,2,3": 0
"1,3,2": 0
"2,1,3": 0
"2,3,1": 0
"3,1,2": 0
"3,2,1": 0
for i in [1..100000]
counts[knuth_shuffle([ 1, 2, 3 ]).join(",")] += 1
for key, val of counts
console.log "#{key}: #{val}"

View file

@ -0,0 +1,5 @@
(defun nshuffle (sequence)
(loop for i from (length sequence) downto 2
do (rotatef (elt sequence (random i))
(elt sequence (1- i))))
sequence)

View file

@ -0,0 +1,16 @@
(defun nshuffle (sequence)
(etypecase sequence
(list (nshuffle-list sequence))
(array (nshuffle-array sequence))))
(defun nshuffle-list (list)
"Shuffle the list using an intermediate vector."
(let ((array (nshuffle-array (coerce list 'vector))))
(declare (dynamic-extent array))
(map-into list 'identity array)))
(defun nshuffle-array (array)
(loop for i from (length array) downto 2
do (rotatef (aref array (random i))
(aref array (1- i)))
finally (return array)))

View file

@ -0,0 +1,9 @@
def knuthShuffle(items : Array)
i = items.size-1
while i > 1
j = Random.rand(0..i)
items.swap(i, j)
i -= 1
end
end

View file

@ -0,0 +1,7 @@
void main() {
import std.stdio, std.random;
auto a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
a.randomShuffle;
a.writeln;
}

View file

@ -0,0 +1,14 @@
import std.stdio, std.algorithm, std.random, std.range;
void knuthShuffle(Range)(Range r)
if (isRandomAccessRange!Range && hasLength!Range &&
hasSwappableElements!Range) {
foreach_reverse (immutable i, ref ri; r[1 .. $ - 1])
ri.swap(r[uniform(0, i + 1)]);
}
void main() {
auto a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
a.knuthShuffle;
a.writeln;
}

View file

@ -0,0 +1,9 @@
procedure KnuthShuffle(a : array of Integer);
var
i, j, tmp : Integer;
begin
for i:=a.High downto 1 do begin
j:=RandomInt(a.Length);
tmp:=a[i]; a[i]:=a[j]; a[j]:=tmp;
end;
end;

View file

@ -0,0 +1,9 @@
def shuffle(array, random) {
for bound in (2..(array.size())).descending() {
def i := random.nextInt(bound)
def swapTo := bound - 1
def t := array[swapTo]
array[swapTo] := array[i]
array[i] := t
}
}

View file

@ -0,0 +1,6 @@
? def arr := [1,2,3,4,5,6,7,8,9,10].diverge()
# value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].diverge()
? shuffle(arr, entropy)
? arr
# value: [4, 5, 2, 9, 7, 8, 1, 3, 6, 10].diverge()

View file

@ -0,0 +1,19 @@
PROGRAM KNUTH_SHUFFLE
CONST CARDS%=52
DIM PACK%[CARDS%]
BEGIN
RANDOMIZE(TIMER)
FOR I%=1 TO CARDS% DO
PACK%[I%]=I%
END FOR
FOR N%=CARDS% TO 2 STEP -1 DO
SWAP(PACK%[N%],PACK%[1+INT(N%*RND(1))])
END FOR
FOR I%=1 TO CARDS% DO
PRINT(PACK%[I%];)
END FOR
PRINT
END PROGRAM

View file

@ -0,0 +1,9 @@
proc shuffle . a[] .
for i = len a[] downto 2
r = random i
swap a[r] a[i]
.
.
arr[] = [ 1 2 3 ]
call shuffle arr[]
print arr[]

View file

@ -0,0 +1,29 @@
Remark- The native '''shuffle''' function implementation in EchoLisp has been replaced by this one.
Thx Rosetta Code.
(lib 'list) ;; for list-permute
;; use "inside-out" algorithm, no swapping needed.
;; returns a random permutation vector of [0 .. n-1]
(define (rpv n (j))
(define v (make-vector n))
(for [(i n)]
(set! j (random (1+ i)))
(when (!= i j) (vector-set! v i [v j]))
(vector-set! v j i))
v)
;; apply to any kind of list
(define (k-shuffle list)
(list-permute list (vector->list (rpv (length list)))))
;; out
(k-shuffle (iota 17))
→ (16 7 11 10 0 9 15 12 13 8 4 2 14 3 6 5 1)
(k-shuffle
'(adrien 🎸 alexandre 🚂 antoine 🍼 ben 📚 georges 📷 julie 🎥 marine 🐼 nathalie 🍕 ))
→ (marine alexandre 🎥 julie 🎸 ben 🍼 nathalie 📚 georges 🚂 antoine adrien 🐼 📷 🍕)
(shuffle ;; native
'(adrien 🎸 alexandre 🚂 antoine 🍼 ben 📚 georges 📷 julie 🎥 marine 🐼 nathalie 🍕 ))
→ (antoine 🎥 🚂 marine adrien nathalie 🍼 🍕 ben 🐼 julie 📷 📚 🎸 alexandre georges)

View file

@ -0,0 +1,17 @@
import "prelude.eg"
import "random.ego"
using System
using List
using Math
def swap =
[ I J XX -> insert I (nth J XX) (insert J (nth I XX) XX) ]
def shuffle =
[ XX ->
let INDICES = reverse (fromto 0 ((length XX) - 1)) in
let SWAPS = map [ I -> I (between 0 I) ] INDICES in
foldr [I J -> swap I J] XX SWAPS ]
def main = shuffle (fromto 1 9)

View file

@ -0,0 +1,55 @@
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
do
test := <<1, 2>>
io.put_string ("Initial: ")
across
test as t
loop
io.put_string (t.item.out + " ")
end
test := shuffle (test)
io.new_line
io.put_string ("Shuffled: ")
across
test as t
loop
io.put_string (t.item.out + " ")
end
end
test: ARRAY [INTEGER]
shuffle (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
-- Array containing the same elements as 'ar' in a shuffled order.
require
more_than_one_element: ar.count > 1
local
count, j, ith: INTEGER
random: V_RANDOM
do
create random
create Result.make_empty
Result.deep_copy (ar)
count := ar.count
across
1 |..| count as c
loop
j := random.bounded_item (c.item, count)
ith := Result [c.item]
Result [c.item] := Result [j]
Result [j] := ith
random.forth
end
ensure
same_elements: across ar as a all Result.has (a.item) end
end
end

View file

@ -0,0 +1,28 @@
import system'routines;
import extensions;
const int MAX = 10;
extension randomOp
{
randomize()
{
var max := self.Length;
for(int i := 0, i < max, i += 1)
{
var j := randomGenerator.eval(i,max);
self.exchange(i,j)
};
^ self
}
}
public program()
{
var a := Array.allocate:MAX.populate:(i => i );
console.printLine(a.randomize())
}

View file

@ -0,0 +1,22 @@
defmodule Knuth do
def shuffle( inputs ) do
n = length( inputs )
{[], acc} = Enum.reduce( n..1, {inputs, []}, &random_move/2 )
acc
end
defp random_move( n, {inputs, acc} ) do
item = Enum.at( inputs, :rand.uniform(n)-1 )
{List.delete( inputs, item ), [item | acc]}
end
end
seq = Enum.to_list( 0..19 )
IO.inspect Knuth.shuffle( seq )
seq = [1,2,3]
Enum.reduce(1..100000, Map.new, fn _,acc ->
k = Knuth.shuffle(seq)
Map.update(acc, k, 1, &(&1+1))
end)
|> Enum.each(fn {k,v} -> IO.inspect {k,v} end)

View file

@ -0,0 +1,14 @@
-module( knuth_shuffle ).
-export( [list/1] ).
list( Inputs ) ->
N = erlang:length( Inputs ),
{[], Acc} = lists:foldl( fun random_move/2, {Inputs, []}, lists:reverse(lists:seq(1, N)) ),
Acc.
random_move( N, {Inputs, Acc} ) ->
Item = lists:nth( random:uniform(N), Inputs ),
{lists:delete(Item, Inputs), [Item | Acc]}.

View file

@ -0,0 +1,23 @@
sequence cards
cards = repeat(0,52)
integer card,temp
puts(1,"Before:\n")
for i = 1 to 52 do
cards[i] = i
printf(1,"%d ",cards[i])
end for
for i = 52 to 1 by -1 do
card = rand(i)
if card != i then
temp = cards[card]
cards[card] = cards[i]
cards[i] = temp
end if
end for
puts(1,"\nAfter:\n")
for i = 1 to 52 do
printf(1,"%d ",cards[i])
end for

View file

@ -0,0 +1,17 @@
open System
let FisherYatesShuffle (initialList : array<'a>) = // '
let availableFlags = Array.init initialList.Length (fun i -> (i, true))
// Which items are available and their indices
let rnd = new Random()
let nextItem nLeft =
let nItem = rnd.Next(0, nLeft) // Index out of available items
let index = // Index in original deck
availableFlags // Go through available array
|> Seq.filter (fun (ndx,f) -> f) // and pick out only the available tuples
|> Seq.nth nItem // Get the one at our chosen index
|> fst // and retrieve it's index into the original array
availableFlags.[index] <- (index, false) // Mark that index as unavailable
initialList.[index] // and return the original item
seq {(initialList.Length) .. -1 .. 1} // Going from the length of the list down to 1
|> Seq.map (fun i -> nextItem i) // yield the next item

View file

@ -0,0 +1,10 @@
let KnuthShuffle (lst : array<'a>) = // '
let Swap i j = // Standard swap
let item = lst.[i]
lst.[i] <- lst.[j]
lst.[j] <- item
let rnd = new Random()
let ln = lst.Length
[0..(ln - 2)] // For all indices except the last
|> Seq.iter (fun i -> Swap i (rnd.Next(i, ln))) // swap th item at the index with a random one following it (or itself)
lst // Return the list shuffled in place

View file

@ -0,0 +1,2 @@
> KnuthShuffle [| "Darrell"; "Marvin"; "Doug"; "Greg"; "Sam"; "Ken" |];;
val it : string array = [|"Marvin"; "Doug"; "Sam"; "Darrell"; "Ken"; "Greg"|]

View file

@ -0,0 +1,4 @@
: randomize ( seq -- seq )
dup length [ dup 1 > ]
[ [ iota random ] [ 1 - ] bi [ pick exchange ] keep ]
while drop ;

View file

@ -0,0 +1,22 @@
class Main
{
static Void knuthShuffle (List array)
{
((array.size-1)..1).each |Int i|
{
r := Int.random(0..i)
array.swap (i, r)
}
}
public static Void main ()
{
List a := [1,2,3,4,5]
knuthShuffle (a)
echo (a)
List b := ["apples", "oranges", "pears", "bananas"]
knuthShuffle (b)
echo (b)
}
}

View file

@ -0,0 +1,15 @@
include random.fs
: shuffle ( deck size -- )
2 swap do
dup i random cells +
over @ over @ swap
rot ! over !
cell+
-1 +loop drop ;
: .array 0 do dup @ . cell+ loop drop ;
create deck 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,
deck 10 2dup shuffle .array

View file

@ -0,0 +1,33 @@
program Knuth_Shuffle
implicit none
integer, parameter :: reps = 1000000
integer :: i, n
integer, dimension(10) :: a, bins = 0, initial = (/ (n, n=1,10) /)
do i = 1, reps
a = initial
call Shuffle(a)
where (a == initial) bins = bins + 1 ! skew tester
end do
write(*, "(10(i8))") bins
! prints 100382 100007 99783 100231 100507 99921 99941 100270 100290 100442
contains
subroutine Shuffle(a)
integer, intent(inout) :: a(:)
integer :: i, randpos, temp
real :: r
do i = size(a), 2, -1
call random_number(r)
randpos = int(r * i) + 1
temp = a(randpos)
a(randpos) = a(i)
a(i) = temp
end do
end subroutine Shuffle
end program Knuth_Shuffle

View file

@ -0,0 +1,77 @@
' version 22-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
Sub knuth_down(a() As Long)
Dim As Long lb = LBound(a)
Dim As ULong n = UBound(a) - lb +1
Dim As ULong i, j
Randomize Timer
For i = n -1 To 1 Step -1
j =Fix(Rnd * (i +1)) ' 0 <= j <= i
Swap a(lb + i), a(lb + j)
Next
End Sub
Sub knuth_up(a() As Long)
Dim As Long lb = LBound(a)
Dim As ULong n = UBound(a) - lb +1
Dim As ULong i, j
Randomize Timer
For i = 0 To n -2
j = Fix(Rnd * (n - i) + i) ' 0 <= j < n-i, + i ==> i <= j < n
Swap a(lb + i), a(lb + j)
Next
End Sub
' ------=< MAIN >=------
Dim As Long i
Dim As Long array(1 To 52), array2(-7 To 7)
For i = 1 To 52 : array(i) = i : Next
Print "Starting array"
For i = 1 To 52
Print Using " ###";array(i);
Next : Print : Print
knuth_down(array())
Print "After Knuth shuffle downwards"
For i = 1 To 52
Print Using " ###";array(i);
Next : Print : Print
For i = LBound(array2) To UBound(array2)
array2(i) = i - LBound(array2) + 1
Next
Print "Starting array, first index <> 0 "
For i = LBound(array2) To UBound(array2)
Print Using " ##";array2(i);
Next : Print : Print
knuth_up(array2())
Print "After Knuth shuffle upwards"
For i = LBound(array2) To UBound(array2)
Print Using " ##";array2(i);
Next : Print : Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

View file

@ -0,0 +1,2 @@
a = [1,2,3]
a.shuffle[]

View file

@ -0,0 +1,9 @@
def shuffle( a ) =
res = array( a )
n = a.length()
for i <- 0:n
r = rnd( i:n )
res(i), res(r) = res(r), res(i)
res.toList()

View file

@ -0,0 +1,25 @@
include "NSLog.incl"
void local fn KnuthShuffle( mutArr as CFMutableArrayRef )
NSUInteger i, j, count
count = len(mutArr)
for i = count-1 to 1 step -1
j = rnd(i+1)-1
MutableArrayExchangeObjects( mutArr, i, j )
next
end fn
randomize
CFMutableArrayRef mutArr
NSUInteger i
mutArr = fn MutableArrayWithObjects( @0, @1, @2, @3, @4, @5, @6, @7, @8, @9, NULL )
NSLog( @"Before shuffle: %@", fn ArrayComponentsJoinedByString( mutArr, @"" ) )
for i = 1 to 100
fn KnuthShuffle( mutArr )
NSLog( @"%@", fn ArrayComponentsJoinedByString( mutArr, @"" ) )
next
HandleEvents

View file

@ -0,0 +1,26 @@
# Return the list L after applying Knuth shuffle. GAP also has the function Shuffle, which does the same.
ShuffleAlt := function(a)
local i, j, n, t;
n := Length(a);
for i in [n, n - 1 .. 2] do
j := Random(1, i);
t := a[i];
a[i] := a[j];
a[j] := t;
od;
return a;
end;
# Return a "Permutation" object (a permutation of 1 .. n).
# They are printed in GAP, in cycle decomposition form.
PermShuffle := n -> PermList(ShuffleAlt([1 .. n]));
ShuffleAlt([1 .. 10]);
# [ 4, 7, 1, 5, 8, 2, 6, 9, 10, 3 ]
PermShuffle(10);
# (1,9)(2,3,6,4,5,10,8,7)
# One may also call the built-in random generator on the symmetric group :
Random(SymmetricGroup(10));
(1,8,2,5,9,6)(3,4,10,7)

View file

@ -0,0 +1,26 @@
Public Sub Main()
Dim iTotal As Integer = 40
Dim iCount, iRand1, iRand2 As Integer
Dim iArray As New Integer[]
For iCount = 0 To iTotal
iArray.add(iCount)
Next
Print "Original = ";
For iCount = 0 To iArray.Max
If iCount = iArray.max Then Print iArray[iCount]; Else Print iArray[iCount] & ",";
Next
For iCount = iTotal DownTo 0
iRand1 = Rand(iTotal)
iRand2 = Rand(iTotal)
Swap iArray[iRand1], iArray[iRand2]
Next
Print gb.NewLine & "Shuffled = ";
For iCount = 0 To iArray.Max
If iCount = iArray.max Then Print iArray[iCount]; Else Print iArray[iCount] & ",";
Next
End

View file

@ -0,0 +1,22 @@
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var a [20]int
for i := range a {
a[i] = i
}
fmt.Println(a)
rand.Seed(time.Now().UnixNano())
for i := len(a) - 1; i >= 1; i-- {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
fmt.Println(a)
}

View file

@ -0,0 +1,48 @@
package main
import (
"fmt"
"math/rand"
"time"
)
// Generic Knuth Shuffle algorithm. In Go, this is done with interface
// types. The parameter s of function shuffle is an interface type.
// Any type satisfying the interface "shuffler" can be shuffled with
// this function. Since the shuffle function uses the random number
// generator, it's nice to seed the generator at program load time.
func init() {
rand.Seed(time.Now().UnixNano())
}
func shuffle(s shuffler) {
for i := s.Len() - 1; i >= 1; i-- {
j := rand.Intn(i + 1)
s.Swap(i, j)
}
}
// Conceptually, a shuffler is an indexed collection of things.
// It requires just two simple methods.
type shuffler interface {
Len() int // number of things in the collection
Swap(i, j int) // swap the two things indexed by i and j
}
// ints is an example of a concrete type implementing the shuffler
// interface.
type ints []int
func (s ints) Len() int { return len(s) }
func (s ints) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Example program. Make an ints collection, fill with sequential numbers,
// print, shuffle, print.
func main() {
a := make(ints, 20)
for i := range a {
a[i] = i
}
fmt.Println(a)
shuffle(a)
fmt.Println(a)
}

View file

@ -0,0 +1,10 @@
def shuffle = { list ->
if (list == null || list.empty) return list
def r = new Random()
def n = list.size()
(n..1).each { i ->
def j = r.nextInt(i)
list[[i-1, j]] = list[[j, i-1]]
}
list
}

View file

@ -0,0 +1,5 @@
def list = [] + (0..20)
println list
println shuffle(list)
println shuffle(list)
println shuffle(list)

View file

@ -0,0 +1,17 @@
import System.Random (randomRIO)
mkRands :: Int -> IO [Int]
mkRands = mapM (randomRIO . (,) 0) . enumFromTo 1 . pred
replaceAt :: Int -> a -> [a] -> [a]
replaceAt i c l =
let (a, b) = splitAt i l
in a ++ c : drop 1 b
swapElems :: (Int, Int) -> [a] -> [a]
swapElems (i, j) xs
| i == j = xs
| otherwise = replaceAt j (xs !! i) $ replaceAt i (xs !! j) xs
knuthShuffle :: [a] -> IO [a]
knuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> mkRands (length xs)

View file

@ -0,0 +1,22 @@
import System.Random (randomRIO)
import Data.Bool (bool)
knuthShuffle :: [a] -> IO [a]
knuthShuffle xs = (foldr swapped xs . zip [1 ..]) <$> randoms (length xs)
swapped :: (Int, Int) -> [a] -> [a]
swapped (i, j) xs =
let go (a, b)
| a == b = xs
| otherwise =
let (m, n) = bool (b, a) (a, b) (b > a)
(l, hi:t) = splitAt m xs
(ys, lo:zs) = splitAt (pred (n - m)) t
in concat [l, lo : ys, hi : zs]
in bool xs (go (i, j)) $ ((&&) . (i <) <*> (j <)) $ length xs
randoms :: Int -> IO [Int]
randoms x = mapM (randomRIO . (,) 0) [1 .. pred x]
main :: IO ()
main = knuthShuffle ['a' .. 'k'] >>= print

View file

@ -0,0 +1,3 @@
knuthShuffleProcess :: (Show a) => [a] -> IO ()
knuthShuffleProcess =
(mapM_ print. reverse =<<). ap (fmap. (. zip [1..]). scanr swapElems) (mkRands. length)

View file

@ -0,0 +1,21 @@
import Data.Array.ST
import Data.STRef
import Control.Monad
import Control.Monad.ST
import Control.Arrow
import System.Random
shuffle :: RandomGen g => [a] -> g -> ([a], g)
shuffle list g = runST $ do
r <- newSTRef g
let rand range = liftM (randomR range) (readSTRef r) >>=
runKleisli (second (Kleisli $ writeSTRef r) >>> arr fst)
a <- newAry (1, len) list
forM_ [len, len - 1 .. 2] $ \n -> do
k <- rand (1, n)
liftM2 (,) (readArray a k) (readArray a n) >>=
runKleisli (Kleisli (writeArray a n) *** Kleisli (writeArray a k))
liftM2 (,) (getElems a) (readSTRef r)
where len = length list
newAry :: (Int, Int) -> [a] -> ST s (STArray s Int a)
newAry = newListArray

View file

@ -0,0 +1,24 @@
100 PROGRAM "Shuffle.bas"
110 RANDOMIZE
120 NUMERIC ARRAY(1 TO 20)
130 CALL INIT(ARRAY)
140 CALL WRITE(ARRAY)
150 CALL SHUFFLE(ARRAY)
160 CALL WRITE(ARRAY)
170 DEF INIT(REF A)
180 FOR I=LBOUND(A) TO UBOUND(A)
190 LET A(I)=I
200 NEXT
210 END DEF
220 DEF WRITE(REF A)
230 FOR I=LBOUND(A) TO UBOUND(A)
240 PRINT A(I);
250 NEXT
260 PRINT
270 END DEF
280 DEF SHUFFLE(REF A)
290 FOR I=UBOUND(A) TO LBOUND(A) STEP-1
300 LET CARD=RND(UBOUND(A)-LBOUND(A))+LBOUND(A)+1
310 IF CARD<>I THEN LET T=A(CARD):LET A(CARD)=A(I):LET A(I)=T
320 NEXT
330 END DEF

View file

@ -0,0 +1,14 @@
procedure main()
show(shuffle([3,1,4,1,5,9,2,6,3]))
show(shuffle("this is a string"))
end
procedure shuffle(A)
every A[i := *A to 1 by -1] :=: A[?i]
return A
end
procedure show(A)
every writes(!A," ")
write()
end

View file

@ -0,0 +1,3 @@
procedure shuffle(A)
every !A :=: ?A
end

View file

@ -0,0 +1,9 @@
[ shuffle a n i j tmp;
for (i = n - 1: i > 0: i--) {
j = random(i + 1) - 1;
tmp = a->j;
a->j = a->i;
a->i = tmp;
}
];

View file

@ -0,0 +1 @@
KS=:{~ (2&{.@[ {`(|.@[)`]} ])/@(,~(,.?@>:))@i.@#

View file

@ -0,0 +1,12 @@
]M=: /:~(1 2 3,:2 3 4),(11 2 3,: 0 11 2),(1 1 1,:1 0),:1 1 1,:1 0 1
1 1 1
1 0 0
1 1 1
1 0 1
1 2 3
2 3 4
11 2 3
0 11 2

View file

@ -0,0 +1,12 @@
KS M
11 2 3
0 11 2
1 1 1
1 0 1
1 1 1
1 0 0
1 2 3
2 3 4

View file

@ -0,0 +1,4 @@
]L=:'aA';'bbB';'cC%$';'dD@'
+--+---+----+---+
|aA|bbB|cC%$|dD@|
+--+---+----+---+

View file

@ -0,0 +1,4 @@
KS L
+--+----+---+---+
|aA|cC%$|dD@|bbB|
+--+----+---+---+

View file

@ -0,0 +1 @@
({~?~@#)

View file

@ -0,0 +1,20 @@
({~?~@#) A
8 7 13 6 10 11 5 9 12
({~?~@#) M
1 1 1
1 0 1
1 2 3
2 3 4
11 2 3
0 11 2
1 1 1
1 0 0
({~?~@#) L
+----+---+--+---+
|cC%$|bbB|aA|dD@|
+----+---+--+---+

View file

@ -0,0 +1,3 @@
process J
fold swap transform array <==> f / g y

View file

@ -0,0 +1,8 @@
(,~(,.?@>:))@i.@# 1+i.6
0 0 0 0 0 0
1 1 0 0 0 0
2 0 0 0 0 0
3 2 0 0 0 0
4 3 0 0 0 0
5 0 0 0 0 0
0 1 2 3 4 5

View file

@ -0,0 +1 @@
2&{.@[ {`(|.@[)`]} ]

View file

@ -0,0 +1 @@
input { ~ shuffled indexes

View file

@ -0,0 +1,4 @@
(|.@; ;&~./@(,. ?@>:)@i.@#)'abcde'
+---+-+---+---+-+-----+
|4 2|3|2 1|1 0|0|abcde|
+---+-+---+---+-+-----+

View file

@ -0,0 +1 @@
KS=: [: > (<@C. >)/@(|.@; ;&~./@(,. ?@>:)@i.@#)

View file

@ -0,0 +1,2 @@
]A=: 5+i.9
5 6 7 8 9 10 11 12 13

Some files were not shown because too many files have changed in this diff Show more