Random
type RandomRandom is a seeded generator of pseudo-random numbers. The same seed gives the same values in the same order on every implementation of Ant, so a simulation, a test, or a game can be run again exactly. Every function but Random.new draws from the generator and changes it, so goroutines that share one without a lock race; Random.fork gives each its own. Generators compare by identity. None is fit for keys or tokens, which take Crypto.randomBytes.
The Random namespace holds one function that makes a generator, four that draw a value from it, one that shuffles an array with it, and one that splits it into two generators whose values never overlap.
Details
- Without a seed, Random.new starts from the host's secure source, and the values differ from run to run.
- A generator is a reference. Every function but
Random.newdraws from it and moves it on, and a second name for it draws from the same sequence. - Give each goroutine its own generator with Random.fork, before the goroutines start.
- For a one-off value that need not repeat, Math.random and Math.randomInt need no generator.
Basic examples
Make a generator with Random.new and draw an int, a float64, and a bool from it:
let r = Random.new(42)
Random.int(r, 1, 7) // 2
Random.float(r) // 0.9246929453253876
Random.bool(r) // truePick an element with Random.pick, and reorder an array in place with Random.shuffle:
let r = Random.new(42)
Random.pick(r, ["rock", "paper", "scissors"]) // "scissors"
let deck = ["A", "K", "Q", "J"]
Random.shuffle(r, deck)
deck // ["A", "J", "K", "Q"]Leave out the seed when the values need not repeat. They differ from run to run:
let r = Random.new()
r.int(1, 7) >= 1 // trueScope
A draw through . reads from the generator:
let r = Random.new(3)
Array.range(0, 10) | Array.map({ r.int(1, 7) }) // [1, 2, 3, 3, 4, 2, 5, 5, 2, 1]A generator renders as Random, never as its state, and compares by identity:
let r = Random.new(1)
r // Random
r == Random.new(1) // false
r == r // trueRandom.pick returns null for an empty array, and draws nothing:
let r = Random.new(42)
let none: Array[string] = []
r.pick(none) // null
r.pick(["a", "b"]) ?? "" // "a"A generator fits in a record field, so a game keeps its randomness with the rest of its state:
type Game = { rng: Random, rolls: Array[int] }
func Game.roll(g: Game): int {
let n = g.rng.int(1, 7)
g.rolls.push(n)
n
}
let game = Game{ rng: Random.new(2024), rolls: [] }
game.roll()
game.roll()
game.roll()
println(game.rolls)[6, 2, 4]Functions by job
Making a generator
- Random.new: a generator from a seed, or from the host's secure source without one
- Random.fork: a second generator that never meets the first, for another goroutine or another part of a program
Drawing values
- Random.int: an
intfromfrom, inclusive, toto, exclusive - Random.float: a
float64in [0, 1) - Random.bool:
trueorfalse, each half the time - Random.pick: an element of an array, or
nullwhen it is empty
Reordering
- Random.shuffle: a random permutation of an array, in place
Applications
Take a sample without repeats: shuffle a copy and keep the front of it. The original array stays as it was:
let names = ["Ann", "Bob", "Cid", "Dee", "Eve", "Fay"]
let r = Random.new(2026)
let pool = [...names]
r.shuffle(pool)
println(pool.slice(0, 3))
println(names)["Bob", "Eve", "Dee"]
["Ann", "Bob", "Cid", "Dee", "Eve", "Fay"]Choose with weights: draw a number below the total weight and walk the table until it falls inside an entry:
type Loot = { name: string, weight: int }
func choose(r: Random, table: Array[Loot]): string {
var roll = r.int(0, table.map({ x.weight }).sum() ?? 0)
for item in table {
if roll < item.weight { return item.name }
roll -= item.weight
}
""
}
let table = [
Loot{ name: "coin", weight: 70 },
Loot{ name: "potion", weight: 25 },
Loot{ name: "sword", weight: 5 },
]
let r = Random.new(9)
let drops = Array.range(0, 1000) | Array.map({ choose(r, table) })
println("coins ${drops.countWhere({ x == "coin" })}, swords ${drops.countWhere({ x == "sword" })}")coins 707, swords 49Generate test inputs from a seed. When a check fails, its message names the seed, which replays the same inputs:
func randomWord(r: Random): string {
let letters = "abcdefghijklmnopqrstuvwxyz".chars()
Array.range(0, r.int(1, 8))
| Array.map({ r.pick(letters) ?? "" })
| String.join("")
}
let seed = 17
let r = Random.new(seed)
let words = Array.range(0, 100) | Array.map({ randomWord(r) })
for word in words {
assert(word.toUpper().toLower() == word, "seed ${seed}: ${word}")
}
println(words.slice(0, 3))["bzh", "y", "qepqlui"]Properties and relations
The same seed gives the same values:
let a = Random.new(99)
let b = Random.new(99)
let xs = Array.range(0, 10) | Array.map({ a.int(0, 1_000_000) })
let ys = Array.range(0, 10) | Array.map({ b.int(0, 1_000_000) })
assert(xs == ys)Random.pick is an index drawn with Random.int:
let xs = ["a", "b", "c", "d", "e"]
let a = Random.new(5)
let b = Random.new(5)
for _ in Array.range(0, 20) {
assert(a.pick(xs) == xs[b.int(0, xs.length())])
}A shuffle keeps every element and only changes the order:
let xs = Array.range(0, 20)
let shuffled = [...xs]
Random.new(8).shuffle(shuffled)
assert(shuffled.sort() == xs)Random.float stays in [0, 1):
let r = Random.new(1)
assert(Array.range(0, 1000).every({ let f = r.float(); f >= 0.0 && f < 1.0 }))Possible issues
A generator made anew for each draw starts over each time, so every draw gives the same value. Make the generator once and pass it along:
Array.range(0, 3) | Array.map({ Random.new(42).int(0, 100) }) // [22, 22, 22]
let r = Random.new(42)
Array.range(0, 3) | Array.map({ r.int(0, 100) }) // [22, 33, 33]A second name for a generator is not a second generator. Both names draw from one sequence:
let r = Random.new(42)
let other = r
other.int(0, 100) // 22
r.int(0, 100) // 33Random.int excludes its upper bound, so r.int(5, 5) has nothing to draw from and panics:
let r = Random.new(1)
r.int(5, 5) // panic: Random.int needs from < to, got 5 and 5Goroutines that draw from one shared generator race. Fork one generator per goroutine before they start:
let root = Random.new(10)
let gens = Array.range(0, 3) | Array.map({ root.fork() })
let rolls = Parallel.map(gens, func(g: Random, ctx: Context): int {
g.int(1, 7)
}, limit: 3) ?? []
println(rolls)[2, 6, 3]A record that holds a generator has no JSON form, and Json.stringify panics on it. Store the seed instead, and make the generator again from it:
type Game = { rng: Random, rolls: Array[int] }
let game = Game{ rng: Random.new(2024), rolls: [] }
Json.stringify(game) // panic: Json.stringify: Random has no JSON formThe values follow from the seed, so anyone who learns it can predict them. Make keys and tokens with Crypto.randomBytes instead.
See also
Random.new · Random.int · Random.float · Random.bool · Random.pick · Random.shuffle · Random.fork · Math.random · Math.randomInt · Crypto.randomBytes
