Algorithm - Random numbers
Most computer languages provide the ability to generate random number sequences. These are pseudo-random number generators because the numbers they produce are not truly random.
Generating a set of unique random numbers
To generate and display a set of unique random numbers, use an array of flags to indicate if a number has already been selected. If a number has already been chosen (indicated by the flag for that number being set to 1), another random number until we get to one which has not yet been selected.
This logic is shown in the algorithm below: The aim is to generate a set of 6 unique lotto numbers from a possible set of 100 numbers, ranging from 1 to 99.
The following generic statement is used to generate a random number between two values (HighValue and LowValue):
Let R = Random (HighValue – LowValue) + LowValue
BEGIN PrintSixUniqueLottoNumbers
FOR i = 1 to 99 ’set all flag values initially to zero
Let Flag(i) = 0
NEXT i
FOR i = 1 to 6 ’do this 6 times to generate 6 numbers
REPEAT
Let r = Random (98) + 1
UNTIL Flag (r) = 0
’keep generating a random number until one is found which has not been used before
Let Flag (r) = 1
’set the flag for this number to show that it has now been used
Display “Your next number is ” r
NEXT i
END PrintSixUniqueLottoNumbers