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
funcroll_dice(seed: i64, count: int): Vector<int>:
rand.Seed(seed)
mut out := Vector {} asVector<int>
repeat count:
out.Push(rand.Int32Range(1, 6))
endret out
endfuncsame(a: Vector<int>, b: Vector<int>): bool:
if a.Len() != b.Len(): retfalseendrepeat a.Len() in i:
if a.Get(i) != b.Get(i): retfalseendendrettrueendfuncmain:
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
Output
same 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
funcmain:
rand.Seed(1)
mut faces := Vector {} asVector<int>
defer faces.Free()
repeat7:
faces.Push(0)
endrepeat60000:
face := rand.Int32Range(1, 6)
faces.Set(face, faces.Get(face) + 1)
endrepeat1to6in face:
count := faces.Get(face)
println"face", face, "near 10000:", count > 9500and count < 10500endmut inside := 0
total := 200000repeat total:
x := rand.Float()
y := rand.Float()
if x * x + y * y < 1.0: inside++ endend
estimate := 4.0 * (inside asf64) / (total asf64)
println"pi estimate within 0.01:", math.Abs(estimate - math.PI) < 0.01end
Output
face 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
funcpick_weighted(names: Vector<str>, weights: Vector<f64>): str:
mut total := 0.0each w in weights:
total += w
endmut x := rand.FloatRange(0.0, total)
repeat names.Len() in i:
x -= weights.Get(i)
if x < 0.0: ret names.Get(i) endendret names.Get(names.Len() - 1)
endfuncmain:
rand.Seed(99)
mut entries := Vector {} asVector<str>
defer entries.Free()
each name in ["Ali", "Sara", "Reza", "Mina", "Omid", "Neda"]:
entries.Push(name)
endmut 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 {} asVector<str>
mut weights := Vector {} asVector<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 := 0mut legendary := 0repeat10000:
drop := pick_weighted(loot, weights)
if drop == "rare": rare++ endif drop == "legendary": legendary++ endendprintln"rare drops near 1800:", rare > 1600and rare < 2000println"legendary drops near 200:", legendary > 120and legendary < 280end
Output
3 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.
coupon: 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
importstrfuncpick(v: Vector<str>, fallback: str): str:
if v.Len() == 0: ret fallback endret rand.ChoiceStr(v)
endfuncbetween(a: i64, b: i64): i64:
ret rand.IntRange(math.MinI64(a, b), math.MaxI64(a, b))
endfuncmain:
rand.SeedAuto()
mut nobody := Vector {} asVector<str>
defer nobody.Free()
println"empty list:", pick(nobody, "nobody")
n := between(10asi64, 1asi64)
println"reversed bounds still work:", n >= 1and n <= 10
word := "سلام"println"bytes in", word + ":", word.Len()
mut letters := Vector {} asVector<str>
defer letters.Free()
each letter in ["س", "ل", "ا", "م"]:
letters.Push(letter)
endprintln"a whole letter:", pick(letters, "").Len() == 2mut mixed := rand.ShuffleStr(letters)
defer mixed.Free()
println"shuffled word keeps every letter:", str.Join(mixed, "").Len() == word.Len()
end
Output
empty list: nobody
reversed bounds still work: true
bytes in سلام: 8
a whole letter: true
shuffled word keeps every letter: true
JobUseA die or a number in a rangeInt32Range, IntRangeA chance, such as 30%BoolP(0.3)A random elementChoiceStr, ChoiceIntSeveral different elementsShuffleStr, then the first nA readable codeTextFrom, DigitA unique identifierUUIDAnything secretcrypto
Starts the generator from a fixed number. With the same seed the sequence of numbers is always the same.
rand-Seed.salam
import rand
funcmain:
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 >= 1and die <= 6
n := rand.Int()
n32 := rand.Int32()
println rand.IntN(10) < 10, n == n, n32 == n32
println rand.IntWithLength(6) >= 100000end
A random decimal number from zero up to, but not including, one.
rand-Float.salam
import rand
funcmain:
a := rand.Float()
println a >= 0.0and a < 1.0
b := rand.FloatRange(10.0, 20.0)
println b >= 10.0and b < 20.0println rand.BoolP(1.0), rand.BoolP(0.0)
flag := rand.Bool()
println flag == trueor flag == falseend
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