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.SeedAutoreseeds fromtime.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 theChoicefunctions on an empty vector stop the program withmodulo by zero. - Treating text as letters.
TextFromandChoiceCharpick 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.
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)
endDice 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.
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
endRaffles 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.
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
endCoupon 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.
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)
endThese 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,ChoiceCharandIntNdivide by the length or byn, so an empty input or a zero stops the program withmodulo by zero. Checklen()first.IntRangeandInt32Rangeneedloto be no larger thanhi. With the bounds reversed they do not fail; they return numbers outside the range. When the bounds come from a user, order them withmath.MinI64andmath.MaxI64.IntWithLength(1)can return 0, and more than 18 digits overflows. For a code of a fixed width,Digitis the safer choice.ChoiceCharandTextFromwork on bytes, and a Persian letter takes two bytes in UTF-8. Put whole letters in a vector and useChoiceStrorShuffleStrinstead.Bytesnever returns a zero byte, because astrends at the first one. Its bytes are 1 to 255, which is fine for filler data and wrong for keys.
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| Job | Use |
|---|---|
| A die or a number in a range | Int32Range, IntRange |
| A chance, such as 30% | BoolP(0.3) |
| A random element | ChoiceStr, ChoiceInt |
| Several different elements | ShuffleStr, then the first n |
| A readable code | TextFrom, Digit |
| A unique identifier | UUID |
| Anything secret | crypto |
Functions
Seed
func Seed(s: i64)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
endSeedAuto
func SeedAuto()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(): i64IntRange is simpler.The example for this item is shown with the ones above: rand-Seed.salam
Int32
func Int32(): intThe example for this item is shown with the ones above: rand-Seed.salam
IntN
func IntN(n: i64): i64n. 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): i64lo 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): intIntRange 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): i64digits 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(): f64import 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
endFloatRange
func FloatRange(lo: f64, hi: f64): f64lo up to, but not including, hi.The example for this item is shown with the ones above: rand-Float.salam
Bool
func Bool(): boolThe example for this item is shown with the ones above: rand-Float.salam
BoolP
func BoolP(p: f64): boolp, between zero and one.The example for this item is shown with the ones above: rand-Float.salam
Bytes
func Bytes(n: int): strn random bytes from 1 to 255 as a str; a zero byte never appears, because it would end the string. Not for keys.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)
endTextFrom
func TextFrom(n: int, charset: str): strn 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): strThe example for this item is shown with the ones above: rand-Text.salam
AlphaUpper
func AlphaUpper(n: int): strThe example for this item is shown with the ones above: rand-Text.salam
AlphaMixed
func AlphaMixed(n: int): strThe example for this item is shown with the ones above: rand-Text.salam
Digit
func Digit(n: int): strThe example for this item is shown with the ones above: rand-Text.salam
Alnum
func Alnum(n: int): strThe example for this item is shown with the ones above: rand-Text.salam
Text
func Text(n: int): str!@#$, for generating a test password.The example for this item is shown with the ones above: rand-Text.salam
HexBytes
func HexBytes(n: int): strn 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(): strThe example for this item is shown with the ones above: rand-Text.salam
Hash160
func Hash160(): strThe example for this item is shown with the ones above: rand-Text.salam
Hash256
func Hash256(): strThe example for this item is shown with the ones above: rand-Text.salam
UUID
func UUID(): strxxxxxxxx-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>): strimport 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()
endChoiceInt
func ChoiceInt(v: Vector<int>): intThe example for this item is shown with the ones above: rand-Choice.salam
ChoiceChar
func ChoiceChar(s: str): strThe example for this item is shown with the ones above: rand-Text.salam
ShuffleStr
func ShuffleStr(v: Vector<str>): Vector<str>The example for this item is shown with the ones above: rand-Choice.salam
ShuffleInt
func ShuffleInt(v: Vector<int>): Vector<int>The example for this item is shown with the ones above: rand-Choice.salam