Last active
December 28, 2015 22:29
-
-
Save Eckankar/7571447 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle i SML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;load "Random"; | |
| local | |
| val rng = Random.newgen () | |
| (* elemFun xs 0 omdanner en liste xs til en funktion f | |
| * Dvs, f i = x, hvis x er på plads i i xs. *) | |
| fun elemFun [] _ _ = raise Domain | |
| | elemFun (x::xs) i n = if n = i then x else elemFun xs (i+1) n | |
| (* ombytter elementerne på plads i og j i liste-funktionen fxs. *) | |
| fun swap fxs i j n = fxs (if n = i then j else if n = j then i else n) | |
| (* laver en Fisher-Yates shuffle af fxs *) | |
| fun doSwaps fxs 0 = fxs | |
| | doSwaps fxs n = | |
| doSwaps (swap fxs n (Random.range (0, n+1) rng)) (n-1) | |
| in | |
| (* blander listen xs med en Fisher-Yates shuffle *) | |
| fun shuffle xs = | |
| let val l = length xs in | |
| List.tabulate (l, doSwaps (elemFun xs 0) (l-1)) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment