Random
import "std/core" (included in import "std") · namespace std.core
Pseudo-random numbers. The generator is xoshiro256**, which is fast, has good statistical quality and gives the same sequence on every platform for the same seed. Random is a shared generator (each thread has its own state); Rng is a separate generator object with its own seed, for when you need several independent or reproducible streams.
Ranges given as (min, max) include both ends for integers.
import "std"
fn main() {
Random.seed(42) // the same numbers on every run
let a = Random.nextInt(1, 6)
Random.seed(42)
print(a == Random.nextInt(1, 6))
let x = Random.nextFloat() // 0 <= x < 1
print(x >= 0.0 && x < 1.0)
let deck: Array<string> = ["A", "K", "Q", "J"]
Random.shuffle(deck)
print(deck.size())
print(deck.contains(Random.choice(deck)))
let rng = new Rng(7) // an independent generator
let roll = rng.nextInt(1, 6)
print(roll >= 1 && roll <= 6)
}true
true
4
true
trueWithout a seed, the shared generator starts from a fixed seed; call Random.seedTime() for different numbers on each run. These generators are not suitable for cryptography (passwords, keys, tokens).
API
class Rng
An independent random number generator with its own state.
Constructors
new Rng(seed: long)
Methods
fn nextInt(min: int, max: int) -> int— A random integer in [min, max] (both inclusive).fn nextLong(min: long, max: long) -> long— A random long in min..max (both included).fn nextFloat() -> float— A random float in [0, 1).fn nextBool() -> bool— true or false, each half of the time.
class Random
Static members
static fn seed(n: long)— Seeds the shared generator, making the sequence repeatable.static fn seedTime()— Seeds the shared generator from the clock.static fn nextInt(min: int, max: int) -> int— A random integer in [min, max] (both inclusive), without modulo bias.static fn nextLong(min: long, max: long) -> long— A random long in min..max (both included).static fn nextFloat() -> float— A random float in [0, 1), or in [min, max).static fn nextFloat(min: float, max: float) -> float— A random float in [min, max).static fn nextBool() -> bool— true or false, each half of the time.static fn chance(p: float) -> bool— true with the given probability (0..1).static fn nextGaussian(mean: float, stddev: float) -> float— Normally distributed (Box–Muller).static fn shuffle<T>(xs: Array<T>)— Shuffle in place (Fisher–Yates) / pick a random element.static fn choice<T>(xs: Array<T>) -> T— A random element (StateError when empty).