std.random

Seeded pseudo-random numbers, choices, and shuffling.

Importuse std.random

Functions

fn seed(n: int)#

Seeds the generator deterministically. Identical seeds yield identical sequences on every backend.

  • n: Seed value; the same seed replays the same sequence.
std.random.seed(42)
println(std.random.next_int()) // -3425465463722317665
std.random.seed(42)
println(std.random.next_int()) // -3425465463722317665 — replayed
fn next_int() -> int#

A uniformly random 64-bit integer (full i64 range). The taught spelling.

std.random.seed(7)
println(std.random.next_int()) // 1021219803524665661
println(std.random.int())      // 3174977118032272916 — same generator
fn int() -> int#

The same draw under a shorter name. int is a primitive-type keyword and is declarable as a function name; this forwards to next_int so there is one implementation, not a dispatch alias.

fn int_range(lo: int, hi: int) -> int#

Uniform integer in [lo, hi); errors unless hi > lo.

  • lo: Inclusive lower bound.
  • hi: Exclusive upper bound; it must exceed lo.
std.random.seed(1)
println(std.random.int_range(1, 7)) // 5 — a die roll: 1..6
println(std.random.int_range(1, 7)) // 5
fn next_float() -> float#

Uniform float in [0.0, 1.0), covering every representable value in range.

std.random.seed(9)
println(std.random.next_float()) // 0.8168788564811628
println(std.random.float())      // 0.30007479681353555 — same generator
fn float() -> float#

The same draw under a shorter name, forwarding to next_float.

fn float_range(lo: float, hi: float) -> float#

Uniform float in [lo, hi).

  • lo: Inclusive lower bound.
  • hi: Exclusive upper bound.
std.random.seed(9)
println(std.random.float_range(-1.0, 1.0)) // 0.6337577129623255
fn coin() -> bool#

A fair coin flip.

std.random.seed(3)
println(std.random.coin()) // true
println(std.random.coin()) // false
fn choice<T>(arr: [T]) -> T#

A uniformly chosen element; errors on an empty array.

  • arr: Values to draw one of; it must not be empty.
std.random.seed(5)
println(std.random.choice(["red", "green", "blue"])) // red
println(std.random.choice(["red", "green", "blue"])) // green
fn shuffle<T>(arr: [T]) -> [T]#

A shuffled copy (Fisher-Yates); the input is not mutated.

  • arr: Values to shuffle; the input is left untouched.
std.random.seed(11)
let deck = [1, 2, 3, 4, 5]
println(std.random.shuffle(deck)) // [5, 1, 2, 3, 4]
println(deck)                     // [1, 2, 3, 4, 5] — input untouched
fn sample<T>(arr: [T], k: int) -> [T]#

k distinct elements drawn without replacement (partial Fisher-Yates).

  • arr: Values to draw from.
  • k: How many distinct elements to take.
std.random.seed(11)
println(std.random.sample(["a", "b", "c", "d"], 2)) // ["d", "a"]