Ink by Example: Random

We can access randomness through two builtins — rand and urand. On Linux they typically map to /dev/random and /dev/urandom.

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 rand.

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 urand. This uses the most secure random number generation interface your system provides to generate a string of random data.

length := 10
log(urand(10))

$ ink random.ink
{0: 0.30464216, 1: 0.46558097, 2: 0.55770918}
{3: 6, 4: 8, 6: 0, 7: 5, 8: 1, 0: 4, 1: 9, 2: 7, 9: 2, 5: 3}
u,,G

Next example: Sorting.