developing-algorithms

Random Number in Range

Given a random number randNum, % can generate a random number within a range:

randNum % 10
Yields 0 – 9:
Possible remainders are 0, 1, …, 8, 9. Remainder 10 is not possible: Ex: 19 % 10 is 9, but 20 % 10 is 0.

randNum % 51
Yields 0 – 50:
Note that % 50 would yield 0 – 49.

(randNum % 9) + 1
Yields 1 – 9:
The % 9 yields 9 possible values 0 – 8, so the + 1 yields 1 – 9.

(randNum % 11) + 20
Yields 20 – 30:
The % 11 yields 11 possible values 0 – 10, so the + 20 yields 20 – 30.