Skip to content

rand

Random integer sampling, string generation, selection, and shuffling.

Functions

int start … -> Int

Samples a uniformly distributed integer from [0, end) or [start, end).

Parameters

NameTypeDescription
start Int Inclusive lower bound, or the exclusive upper bound when end is omitted.
end? Int Exclusive upper bound.

Errors

ValueError if end <= 0, or end <= start when both are given.

Example

assert_eq (int 1) 0
let n = int 10 20
assert ((n >= 10) && (n < 20))

pick[T] collection -> T

Selects one random element from an array.

Parameters

NameTypeDescription
collection BaseArray[T] Source array.

Errors

ValueError if collection is empty.

Example

let item = pick [1, 2, 3]
assert ([1, 2, 3].contains $item)

shuffle[T] array

Shuffles an array in place using a uniform Fisher-Yates pass.

Parameters

NameTypeDescription
array Array[T] Array to mutate.

Example

let items = [1, 2, 3, 4]
shuffle $items
let sorted = [...items]
sorted.sort()
assert_eq $sorted [1, 2, 3, 4]
Open in playground

string len … -> Str

Generates a random string by sampling characters from alphabet.

Parameters

NameTypeDescription
len Int Number of characters to emit.
:alphabet? Str Characters to sample from.
:alphabet

The alphabet is interpreted as characters, not raw UTF-8 bytes. When omitted, it is _-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.

Errors

ValueError if len is negative or alphabet is empty.

Example

let token = string 12
assert_eq $token.len 12

let text = string 4 alphabet: "åß"
assert_eq $text.len 8