Docs/Data & text

Random numbers

Random numbers, choices, and shuffles.

On this page

valk.random makes fast pseudo-random numbers. Each thread has its own generator, seeded from the operating system.

Numbers and choices#

Valk
use valk.random

fn main() {
    let roll = random.between(1, 6)   // 1 to 6, both included
    let index = random.below(10)      // 0 to 9
    let f = random.fraction()         // 0 up to but not including 1
    if random.chance(0.25) {          // true one time in four
        println("lucky")
    }
    println(roll >= 1 && roll <= 6)   // true
}
Function Returns
between(min, max) An int from min to max, both included
below(n) A uint from 0 up to but not including n
fraction() A float from 0 up to but not including 1
chance(p) true with probability p
next() 64 random bits as a u64

Shuffle and pick#

Valk
use valk.random

fn main() {
    let cards = Array[String]{ "A", "K", "Q", "J" }
    cards.shuffle()
    let mixed = cards.shuffled()      // a shuffled copy
    let pick = cards[random.below(cards.length)]
    println(mixed.length)             // 4
}

Repeatable numbers#

Valk
use valk.random

fn main() {
    let rng = random.Rng.new(42)
    let first = rng.between(1, 100)
    rng.reseed(42)
    println(rng.between(1, 100) == first) // true

    let deck = Array[int]{ 1, 2, 3, 4, 5 }
    deck.shuffle(rng)
}

random.seed(42) seeds the thread's generator, so the numbers after it repeat from run to run. random.Rng.new(seed) makes a separate generator with the same methods, which shuffle and shuffled also accept. Rng.from_entropy() seeds one from the operating system.

Secure random values#

These numbers can be predicted by someone who sees enough of them. For keys, tokens and passwords use a secure source:

Valk
use valk.crypto

fn main() {
    let token = String.random(32)        // letters and digits
    let key = crypto.random_bytes(32)    // raw bytes
    let id = uint.random()
    println(token.length)                // 32
}

See Cryptography.