Suppose you want to make a random 9 digit number, using every number from 1 to 9 exactly once. You have a process called random(top) that gives a random number up to top (if top was 5, it would give random numbers from 1 to 5)
a) How could you do this?
b) If top couldn't be more than 9, how could you do this using random(top) only 9 times (or less)?
Create an int array of size 9 indexed by 0 ... 8.
Until the array is empty perform the following steps:
Make a call to random and store the result
value = random(9);
Access the element of the array corresponding to
int_array[(value - 1)]
As you use the values from the array replace them with a sentinel, such as -999. You could check to make sure they have not been used as follows:
if(int_array[value - 1] != -999)
<.. use to build random number ..>
<.. do not use. repeat process ..>
Repeat this until the 9-digit random number is built.
Posted by daniel
on 2003-05-04 15:11:53