Randomness
Dice, cards, loot tables and unique ids all need random numbers — but not the same kind. This lesson uses a seeded generator, shuffles a deck correctly, draws with weights, makes unique ids, and shows when ordinary random numbers are not safe.
What you will learn#
- the
Randomclass and the seed, - throwing dice and checking that they are fair,
- shuffling with the Fisher–Yates algorithm,
- weighted choices,
Guidfor unique ids,- secure randomness for passwords and tokens.
The program#
# randomness - seeds, dice, shuffling cards, weighted choices, unique ids, and when "random" must be secure
load "dotnet.ring"
using {
"System"
"System.Security.Cryptography"
}
func main
# 1. Random with a SEED gives the same sequence every time: perfect for tests and for repeating a simulation
oFirst = new Random(2024)
oSecond = new Random(2024)
? "1. two generators with the same seed: " + oFirst.@Next(100) + " " + oFirst.@Next(100) + " " + oFirst.@Next(100) + " and " + oSecond.@Next(100) + " " + oSecond.@Next(100) + " " + oSecond.@Next(100)
# 2. @Next(max) is 0..max-1. A die is @Next(6) + 1. Throw it 6000 times: each side comes up about 1000 times.
oRandom = new Random(7)
aCount = [0,0,0,0,0,0]
for nThrow = 1 to 6000
nSide = oRandom.@Next(6) + 1
aCount[nSide]++
next
? nl + "2. 6000 throws of a die: " + joinWith(aCount," ")
lFair = True
for nCount in aCount
if nCount < 900 or nCount > 1100
lFair = False
ok
next
? " every side between 900 and 1100 times? " + yesNo(lFair)
# 3. Shuffling a deck: the Fisher-Yates way. Go from the end; swap each card with a random card from the start up to it.
aDeck = []
for nCard = 1 to 10
aDeck + nCard
next
for nIndex = len(aDeck) to 2 step -1
nOther = oRandom.@Next(nIndex) + 1
aTemp = aDeck[nIndex]
aDeck[nIndex] = aDeck[nOther]
aDeck[nOther] = aTemp
next
? nl + "3. a shuffled deck of 10: " + joinWith(aDeck," ") + " (still 10 different cards: " + yesNo(len(aDeck) = 10 and sumOf(aDeck) = 55) + ")"
# 4. A weighted choice: some outcomes are more likely. Pick a number below the total and walk through the weights.
aItems = [["common",70],["rare",25],["legendary",5]]
aWon = [0,0,0]
for nDraw = 1 to 10000
nPick = oRandom.@Next(100)
nSum = 0
for nIndex = 1 to len(aItems)
nSum += aItems[nIndex][2]
if nPick < nSum
aWon[nIndex]++
exit
ok
next
next
? nl + "4. 10000 draws with chances 70 / 25 / 5 percent:"
for nIndex = 1 to 3
? " " + padRight(aItems[nIndex][1],10) + aWon[nIndex]
next
# 5. Unique identifiers: a Guid is 128 random bits; the chance of two equal Guids is practically zero
oGuid = new Guid().NewGuid()
cGuid = oGuid.ToString()
? nl + "5. a Guid has " + len(cGuid) + " characters (8-4-4-4-12 hexadecimal digits); two new Guids are different: " + yesNo(new Guid().NewGuid().ToString() != new Guid().NewGuid().ToString())
# 6. Random is predictable: with a few outputs one can calculate the next ones. Passwords, tokens and keys need real randomness.
oSecure = new RandomNumberGenerator()
nSecure = oSecure.GetInt32(1000000)
? nl + "6. a secure number from RandomNumberGenerator.GetInt32: " + yesNo(nSecure >= 0 and nSecure < 1000000) + " (in range); a different one every run"
func sumOf aList
nSum = 0
for nItem in aList
nSum += nItem
next
return nSum
func joinWith aList, cSeparator
cText = ""
for xItem in aList
if cText != ""
cText += cSeparator
ok
cText += xItem
next
return cText
func padRight cText, nWidth
while len(cText) < nWidth
cText += " "
end
return cText
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. two generators with the same seed: 11 69 51 and 11 69 51
2. 6000 throws of a die: 1051 974 1022 1000 1004 949
every side between 900 and 1100 times? yes
3. a shuffled deck of 10: 9 6 1 10 2 3 4 8 7 5 (still 10 different cards: yes)
4. 10000 draws with chances 70 / 25 / 5 percent:
common 6954
rare 2577
legendary 469
5. a Guid has 36 characters (8-4-4-4-12 hexadecimal digits); two new Guids are different: yes
6. a secure number from RandomNumberGenerator.GetInt32: yes (in range); a different one every runHow it works#
Random numbers are calculated#
Random does not roll dice: it follows a formula that gives numbers that look random. The starting value is the seed. The same seed gives the same numbers (step 1), which is exactly what you want for a test or a replay: a game level that is the same for the same seed, a simulation you can repeat. Without a seed, new Random(NULL) starts from the clock. @Next(100) gives 0…99 (Next is a Ring keyword, so the method is called @Next).
Dice#
@Next(6) + 1 is 1…6. With 6,000 throws every side comes up about 1,000 times; the test in the program accepts 900–1100. About is the important word: with a random generator you test that the result is in a range, not that it is a fixed number — unless you fix the seed.
Shuffling#
A wrong shuffle is a classic bug. Fisher–Yates is right: go from the last card to the second; swap the card with a random card from the first position up to itself. Every order is equally likely. Swapping each card with any random card (@Next(10) every time) looks similar but gives some orders more often than others.
Weighted choice#
To draw "common" 70 %, "rare" 25 % and "legendary" 5 % of the time, pick a number from 0 to 99 and walk through the weights adding them up until the number is below the sum. The output shows 6,954 / 2,577 / 469 for 10,000 draws, close to the expected 7,000 / 2,500 / 500.
Guid#
A Guid has 128 random bits, written as 36 characters. Two Guids are equal with a probability so small that nobody ever sees it, so you can create ids without asking a database or another computer. Use them as keys for records created on different machines.
When it must be secure#
Because Random is a formula, a person who sees a few of its numbers can calculate the next ones. For passwords, tokens, keys and anything that guards a secret use RandomNumberGenerator (the tutorial Hashing and encryption and the tutorial Login, sessions and cookies use it). Rule of thumb: games and simulations → Random; security → RandomNumberGenerator.
What you learned#
- seeds and repeatable randomness,
- ranges and testing random code,
- Fisher–Yates shuffling,
- weighted choice,
Guid,RandomagainstRandomNumberGenerator.
Exercises#
- Throw two dice 36,000 times and print how often each sum (2…12) appears.
- Write a password generator with
RandomNumberGenerator.GetInt32and a list of allowed characters. - Shuffle a deck of 52 cards (numbers 1–52) and deal four hands of five.
- Estimate the probability of at least one six in four throws by simulation, then calculate it exactly.