Standard library · Numbers and collections

rand

Random numbers, text and choices: dice, one-time codes, unique identifiers and shuffling a list.

import rand

The rand package makes everyday random values: a number in a range, a chance, a pick from a list, a shuffled order, a readable code and a UUID. Use it for games, simulations, sample data, load tests and identifiers that only need to be unique. For anything an attacker must not guess, use crypto; to summarise the numbers you drew (mean, spread, median), use stats.

All functions share one generator: a 64-bit linear congruential generator (the state step of PCG, without its output permutation). It seeds itself from the clock the first time you use it, so a plain program already gets different numbers on each run. Two things change that:

  • Seed(n) starts from a fixed number, and the same seed always gives the same sequence. That is what a test or a reproducible simulation wants.
  • SeedAuto reseeds from time.Now(), which counts whole seconds. Two programs started in the same second get the same numbers, so do not rely on it to give parallel workers different streams; seed each one with its own number instead.

What people get wrong most often:

  • Using it for secrets. The next value follows from the previous ones, and the state is seeded from a clock in seconds. Session tokens, reset links and API keys belong to crypto.
  • Calling it on an empty input or a zero bound. IntN(0) and the Choice functions on an empty vector stop the program with modulo by zero.
  • Treating text as letters. TextFrom and ChoiceChar pick bytes, so a Persian alphabet comes out as broken characters.

The generator is one global value with no lock. Threads that draw at the same time can get the same number; draw in one thread, or give each thread its own seeded run.

The examples on this page print properties of the values, such as whether they fall in a range, rather than the values themselves, so the output is the same on every run.

Repeatable runs for tests

A random program is hard to test because its output changes. Seed fixes the starting point, so the same seed always produces the same sequence. Seed once at the start of a test and compare the results with what you expect. Leave the seed out of the real program, which then seeds itself from the clock. A fixed seed only repeats on the same version of Salam, so compare properties or a whole run, not numbers copied from an old release.

rand-guide-tests.salam
import rand

func roll_dice(seed: i64, count: int): Vector<int>:
    rand.Seed(seed)
    mut out := Vector {} as Vector<int>
    repeat count:
        out.Push(rand.Int32Range(1, 6))
    end
    ret out
end

func same(a: Vector<int>, b: Vector<int>): bool:
    if a.Len() != b.Len(): ret false end
    repeat a.Len() in i:
        if a.Get(i) != b.Get(i): ret false end
    end
    ret true
end

func main:
    mut first := roll_dice(2026, 20)
    mut second := roll_dice(2026, 20)
    mut other := roll_dice(7, 20)
    defer first.Free()
    defer second.Free()
    defer other.Free()
    println "same seed, same rolls:", same(first, second)
    println "other seed, same rolls:", same(first, other)
end
Outputsame seed, same rolls: true other seed, same rolls: false

Dice and simulations

Int32Range gives a whole number with both ends included, which is exactly a die. Float gives a value from zero up to one, the building block of a Monte Carlo estimate: here, the share of random points that land inside a quarter circle gives an approximation of pi. With enough samples each face comes up close to one sixth of the time.

rand-guide-simulation.salam
import rand
import math

func main:
    rand.Seed(1)
    mut faces := Vector {} as Vector<int>
    defer faces.Free()
    repeat 7:
        faces.Push(0)
    end
    repeat 60000:
        face := rand.Int32Range(1, 6)
        faces.Set(face, faces.Get(face) + 1)
    end
    repeat 1 to 6 in face:
        count := faces.Get(face)
        println "face", face, "near 10000:", count > 9500 and count < 10500
    end
    mut inside := 0
    total := 200000
    repeat total:
        x := rand.Float()
        y := rand.Float()
        if x * x + y * y < 1.0: inside++ end
    end
    estimate := 4.0 * (inside as f64) / (total as f64)
    println "pi estimate within 0.01:", math.Abs(estimate - math.PI) < 0.01
end
Outputface 1 near 10000: true face 2 near 10000: true face 3 near 10000: true face 4 near 10000: true face 5 near 10000: true face 6 near 10000: true pi estimate within 0.01: true

Raffles and weighted picks

To pick several different winners, shuffle a copy with ShuffleStr and take the first few; the original vector stays as it was. For a weighted choice, such as loot that is common 80% of the time, draw a number in the range of the total weight and walk through the weights until it runs out.

rand-guide-draw.salam
import rand

func pick_weighted(names: Vector<str>, weights: Vector<f64>): str:
    mut total := 0.0
    each w in weights:
        total += w
    end
    mut x := rand.FloatRange(0.0, total)
    repeat names.Len() in i:
        x -= weights.Get(i)
        if x < 0.0: ret names.Get(i) end
    end
    ret names.Get(names.Len() - 1)
end

func main:
    rand.Seed(99)
    mut entries := Vector {} as Vector<str>
    defer entries.Free()
    each name in ["Ali", "Sara", "Reza", "Mina", "Omid", "Neda"]:
        entries.Push(name)
    end
    mut order := rand.ShuffleStr(entries)
    defer order.Free()
    winners := [order.Get(0), order.Get(1), order.Get(2)]
    println "3 winners, all different:", winners[0] != winners[1] and winners[1] != winners[2] and winners[0] != winners[2]
    println "entries untouched:", entries.Get(0), entries.Len()
    mut loot := Vector {} as Vector<str>
    mut weights := Vector {} as Vector<f64>
    defer loot.Free()
    defer weights.Free()
    loot.Push("common")
    weights.Push(80.0)
    loot.Push("rare")
    weights.Push(18.0)
    loot.Push("legendary")
    weights.Push(2.0)
    mut rare := 0
    mut legendary := 0
    repeat 10000:
        drop := pick_weighted(loot, weights)
        if drop == "rare": rare++ end
        if drop == "legendary": legendary++ end
    end
    println "rare drops near 1800:", rare > 1600 and rare < 2000
    println "legendary drops near 200:", legendary > 120 and legendary < 280
end
Output3 winners, all different: true entries untouched: Ali 6 rare drops near 1800: true legendary drops near 200: true

Coupon codes, PINs and IDs

TextFrom builds text from your own alphabet. Leaving out characters that look alike, such as 0 and O or 1 and I, makes a code people can read out loud. Digit keeps leading zeros, which a number from IntWithLength cannot, and UUID makes a version 4 identifier.

rand-guide-codes.salam
import rand
import str

const ALPHABET := "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"

func coupon(groups: int): str:
    mut parts := Vector {} as Vector<str>
    defer parts.Free()
    repeat groups:
        parts.Push(rand.TextFrom(4, ALPHABET))
    end
    ret str.Join(parts, "-")
end

func only_from(s: str, allowed: str): bool:
    repeat s.Len() in i:
        if str.Contains(allowed, s.Substr(i, 1)) == false: ret false end
    end
    ret true
end

func main:
    rand.SeedAuto()
    code := coupon(3)
    println "coupon:", code.Len(), "characters, dashes:", code.Substr(4, 1) + code.Substr(9, 1)
    println "no 0, O, 1 or I:", only_from(str.Replace(code, "-", ""), ALPHABET)
    sms := rand.Digit(6)
    println "sms code:", sms.Len(), "digits,", only_from(sms, "0123456789")
    pin := rand.IntWithLength(4)
    println "pin in 1000..9999:", pin >= 1000 and pin <= 9999
    println "uuid version:", rand.UUID().Substr(14, 1)
end
Outputcoupon: 14 characters, dashes: -- no 0, O, 1 or I: true sms code: 6 digits, true pin in 1000..9999: true uuid version: 4

These values are fine for coupons, test data and file names, but anyone who sees a few of them could predict the next. For a password reset link, an API key or a session token, use crypto.RandomToken or crypto.RandomHex from crypto.

Pitfalls

A few cases need a guard of your own:

  • ChoiceStr, ChoiceInt, ChoiceChar and IntN divide by the length or by n, so an empty input or a zero stops the program with modulo by zero. Check len() first.
  • IntRange and Int32Range need lo to be no larger than hi. With the bounds reversed they do not fail; they return numbers outside the range. When the bounds come from a user, order them with math.MinI64 and math.MaxI64.
  • IntWithLength(1) can return 0, and more than 18 digits overflows. For a code of a fixed width, Digit is the safer choice.
  • ChoiceChar and TextFrom work on bytes, and a Persian letter takes two bytes in UTF-8. Put whole letters in a vector and use ChoiceStr or ShuffleStr instead.
  • Bytes never returns a zero byte, because a str ends at the first one. Its bytes are 1 to 255, which is fine for filler data and wrong for keys.
rand-guide-safe.salam
import rand
import math
import str

func pick(v: Vector<str>, fallback: str): str:
    if v.Len() == 0: ret fallback end
    ret rand.ChoiceStr(v)
end

func between(a: i64, b: i64): i64:
    ret rand.IntRange(math.MinI64(a, b), math.MaxI64(a, b))
end

func main:
    rand.SeedAuto()
    mut nobody := Vector {} as Vector<str>
    defer nobody.Free()
    println "empty list:", pick(nobody, "nobody")
    n := between(10 as i64, 1 as i64)
    println "reversed bounds still work:", n >= 1 and n <= 10
    word := "سلام"
    println "bytes in", word + ":", word.Len()
    mut letters := Vector {} as Vector<str>
    defer letters.Free()
    each letter in ["س", "ل", "ا", "م"]:
        letters.Push(letter)
    end
    println "a whole letter:", pick(letters, "").Len() == 2
    mut mixed := rand.ShuffleStr(letters)
    defer mixed.Free()
    println "shuffled word keeps every letter:", str.Join(mixed, "").Len() == word.Len()
end
Outputempty list: nobody reversed bounds still work: true bytes in سلام: 8 a whole letter: true shuffled word keeps every letter: true
JobUse
A die or a number in a rangeInt32Range, IntRange
A chance, such as 30%BoolP(0.3)
A random elementChoiceStr, ChoiceInt
Several different elementsShuffleStr, then the first n
A readable codeTextFrom, Digit
A unique identifierUUID
Anything secretcrypto

Functions

Seed

func Seed(s: i64)
Starts the generator from a fixed number. With the same seed the sequence of numbers is always the same.
rand-Seed.salam
import rand

func main:
    rand.Seed(42)
    a := rand.IntRange(1, 100)
    rand.Seed(42)
    b := rand.IntRange(1, 100)
    println a == b
    rand.SeedAuto()
    die := rand.Int32Range(1, 6)
    println die >= 1 and die <= 6
    n := rand.Int()
    n32 := rand.Int32()
    println rand.IntN(10) < 10, n == n, n32 == n32
    println rand.IntWithLength(6) >= 100000
end
Outputtrue true true true true true

SeedAuto

func SeedAuto()
Reseeds the generator from time.Now(), in whole seconds. The generator does this by itself on first use, so call it only to start over after a Seed.

The example for this item is shown with the ones above: rand-Seed.salam

Int

func Int(): i64
A random whole number from 0 to 263-1; it is never negative. For a number in a particular range, IntRange is simpler.

The example for this item is shown with the ones above: rand-Seed.salam

Int32

func Int32(): int
A random whole number from 0 to 231-1; it is never negative.

The example for this item is shown with the ones above: rand-Seed.salam

IntN

func IntN(n: i64): i64
A random number from zero to one less than n. n must be positive; 0 stops the program.

The example for this item is shown with the ones above: rand-Seed.salam

IntRange

func IntRange(lo: i64, hi: i64): i64
A random number from lo to hi, both included. lo must not be larger than hi.

The example for this item is shown with the ones above: rand-Seed.salam

Int32Range

func Int32Range(lo: int, hi: int): int
Like IntRange with a 32-bit result; for a die, 1 to 6.

The example for this item is shown with the ones above: rand-Seed.salam

IntWithLength

func IntWithLength(digits: int): i64
A random number with exactly digits digits, such as 1000 to 9999 for 4. For 1 (or less) it returns 0 to 9, and above 18 it overflows.

The example for this item is shown with the ones above: rand-Seed.salam

Float

func Float(): f64
A random decimal number from zero up to, but not including, one.
rand-Float.salam
import rand

func main:
    a := rand.Float()
    println a >= 0.0 and a < 1.0
    b := rand.FloatRange(10.0, 20.0)
    println b >= 10.0 and b < 20.0
    println rand.BoolP(1.0), rand.BoolP(0.0)
    flag := rand.Bool()
    println flag == true or flag == false
end
Outputtrue true true false true

FloatRange

func FloatRange(lo: f64, hi: f64): f64
A random decimal number from lo up to, but not including, hi.

The example for this item is shown with the ones above: rand-Float.salam

Bool

func Bool(): bool
True or false, each with probability one half.

The example for this item is shown with the ones above: rand-Float.salam

BoolP

func BoolP(p: f64): bool
Returns true with probability p, between zero and one.

The example for this item is shown with the ones above: rand-Float.salam

Bytes

func Bytes(n: int): str
n random bytes from 1 to 255 as a str; a zero byte never appears, because it would end the string. Not for keys.
rand-Text.salam
import rand
import str

func main:
    println rand.Alpha(8).Len(), rand.AlphaUpper(8).Len(), rand.AlphaMixed(8).Len()
    println rand.Digit(6).Len(), rand.Alnum(12).Len(), rand.Text(10).Len()
    println rand.TextFrom(5, "ab").Len(), str.Contains("ab", rand.ChoiceChar("ab"))
    println rand.Bytes(4).Len(), rand.HexBytes(4).Len()
    println rand.Hash().Len(), rand.Hash160().Len(), rand.Hash256().Len()
    id := rand.UUID()
    println id.Len(), id.Substr(14, 1)
end
Output8 8 8 6 12 10 5 true 4 8 32 40 64 36 4

TextFrom

func TextFrom(n: int, charset: str): str
Builds text of n bytes, each picked from the bytes of charset. Use an ASCII charset; a multi-byte letter would be split. Empty charset or n of 0 gives empty text.

The example for this item is shown with the ones above: rand-Text.salam

Alpha

func Alpha(n: int): str
Text of lower case English letters.

The example for this item is shown with the ones above: rand-Text.salam

AlphaUpper

func AlphaUpper(n: int): str
Text of upper case English letters.

The example for this item is shown with the ones above: rand-Text.salam

AlphaMixed

func AlphaMixed(n: int): str
Text of upper and lower case English letters.

The example for this item is shown with the ones above: rand-Text.salam

Digit

func Digit(n: int): str
Text of digits only, for a one-time code.

The example for this item is shown with the ones above: rand-Text.salam

Alnum

func Alnum(n: int): str
Text of English letters and digits.

The example for this item is shown with the ones above: rand-Text.salam

Text

func Text(n: int): str
Text of English letters, digits and punctuation such as !@#$, for generating a test password.

The example for this item is shown with the ones above: rand-Text.salam

HexBytes

func HexBytes(n: int): str
n random bytes as hexadecimal text, two characters per byte.

The example for this item is shown with the ones above: rand-Text.salam

Hash

func Hash(): str
A random 32-character hexadecimal string (16 bytes). It is not a hash of anything; the name only describes the shape.

The example for this item is shown with the ones above: rand-Text.salam

Hash160

func Hash160(): str
A random 40-character hexadecimal string, 160 bits.

The example for this item is shown with the ones above: rand-Text.salam

Hash256

func Hash256(): str
A random 64-character hexadecimal string, 256 bits.

The example for this item is shown with the ones above: rand-Text.salam

UUID

func UUID(): str
Builds a random version 4 UUID in lower case, of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where y is 8, 9, a or b.

The example for this item is shown with the ones above: rand-Text.salam

ChoiceStr

func ChoiceStr(v: Vector<str>): str
Returns a random element of a vector of strings. An empty vector stops the program.
rand-Choice.salam
import rand

func main:
    mut names := Vector {} as Vector<str>
    defer names.Free()
    names.Push("Ali")
    names.Push("Sara")
    names.Push("Reza")
    winner := rand.ChoiceStr(names)
    println winner == "Ali" or winner == "Sara" or winner == "Reza"
    mut numbers := Vector {} as Vector<int>
    defer numbers.Free()
    repeat 1 to 5 in i:
        numbers.Push(i)
    end
    println rand.ChoiceInt(numbers) <= 5
    shuffled := rand.ShuffleInt(numbers)
    mut total := 0
    each n in shuffled:
        total += n
    end
    println shuffled.Len(), total
    println rand.ShuffleStr(names).Len()
end
Outputtrue true 5 15 3

ChoiceInt

func ChoiceInt(v: Vector<int>): int
Returns a random element of a vector of numbers. An empty vector stops the program.

The example for this item is shown with the ones above: rand-Choice.salam

ChoiceChar

func ChoiceChar(s: str): str
Returns one random byte of a string as a one-byte string. Only right for ASCII text.

The example for this item is shown with the ones above: rand-Text.salam

ShuffleStr

func ShuffleStr(v: Vector<str>): Vector<str>
Returns a shuffled copy of a vector of strings (a Fisher-Yates shuffle), leaving the vector itself alone. Free the copy when done.

The example for this item is shown with the ones above: rand-Choice.salam

ShuffleInt

func ShuffleInt(v: Vector<int>): Vector<int>
Returns a shuffled copy of a vector of numbers, leaving the vector itself alone.

The example for this item is shown with the ones above: rand-Choice.salam