Last active
December 28, 2015 22:29
-
-
Save chrene/7572487 to your computer and use it in GitHub Desktop.
List Shuffler
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"; | |
(* Laver en liste fra 0 til og med n *) | |
fun listTo n = List.tabulate(n+1, fn n => n); | |
(* Skifter rækkefølgen af elementerne i en liste tilfældigt. | |
(Blander listen) *) | |
fun shuffle(xs) = | |
let | |
val rg = Random.newgen() | |
fun shuffle'([]) = [] | |
| shuffle'([x]) = [x] | |
| shuffle'(x::xs) = | |
let | |
(* Find et tilfældigt index *) | |
val index = Random.range(0, length(x::xs)) rg | |
(* Gem elementet ved det index *) | |
val i = List.nth(x::xs, index) | |
in | |
(* Tag det element og sæt det foran værdien af et rekursivt kald *) | |
(* Her fjernes elementet også fra listen, så vi gør listen mindre *) | |
i::shuffle'((List.take(x::xs, index) @ List.drop(x::xs, index+1))) | |
end | |
in | |
shuffle'(xs) | |
end; | |
val numbers = listTo 10; | |
val bingoList = shuffle(numbers); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment