Skip to content

Instantly share code, notes, and snippets.

@Hugoberry
Last active February 1, 2017 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hugoberry/28737cc738aa54ea72f56a4a4c3061f1 to your computer and use it in GitHub Desktop.
Save Hugoberry/28737cc738aa54ea72f56a4a4c3061f1 to your computer and use it in GitHub Desktop.
The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite set—in plain terms, the algorithm shuffles the set. The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain. The algorithm produces an unbiase…
(n) =>
let
swapAnyOrder = (_,from,to)=> if from = to then _ else
(if from < to then swap(_,from,to) else swap(_,to,from)),
swap = (_,from,to)=> List.Range(_,0,from)
&{_{to}}
&List.Range(_,from+1,to-from-1)
&{_{from}}
&List.Range(_,to+1)
in
List.Accumulate({0..(n-2)},{0..n},(_,iterator)=>
swapAnyOrder(List.Buffer(_),
Number.Round(Number.RandomBetween(iterator,n)),
iterator
)
)
@Hugoberry
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment