2A.06 – Random Number Generation


Previous: 2A.05 - Arrays

Random numbers are often used in games when the programmer wants an unknown element in the code.

In pseudo-code we use RANDOM_INT(x, y) to generate a random integer from x to y

Example 1 shows how the RANDOM_INT function can be used to simulate rolling a die.

Example 1
num ← RANDOM_INT(1, 6)
OUTPUT num

Example 2 shows how the RANDOM_INT function can be used to simulate a coin toss.

Example 2
coin = ["Heads", "Tails"]
num ← RANDOM_INT(0, 1)
OUTPUT coin[num]



How would we simulate rolling a 20-sided die in pseudo-code?

Tap/click to reveal RANDOM_INT(1, 20)





Next: 2A.07 - Selection



© Rujul Nayak 2024-