We can access randomness through two builtins — |
|
std := load('../vendor/std') range := std.range each := std.each log := std.log |
|
For a random number in the range [0, 1) — including zero but excluding one — we use |
choices := [rand(), rand(), rand()] log(choices) |
We can use this to shuffle a list using the Fisher-Yates algorithm. |
` an ordered list ` numbers := range(0, 10, 1) shuffle := list => ( each(list, (val, i) => ( pick := floor(rand() * (len(list) - i - 1)) current := len(list) - 1 - i tmp := list.(current) list.(current) := list.(pick) list.(pick) := tmp )) list ) log(shuffle(numbers)) |
For cryptographically secure randomness, use |
length := 10 log(urand(10)) |
$ ink random.ink {0: 0.83260429, 1: 0.90562506, 2: 0.83247869} {1: 0, 4: 9, 9: 8, 7: 5, 8: 3, 0: 7, 2: 1, 3: 6, 5: 4, 6: 2} :IjLv ·ê·Y |
Next example: Sorting.