All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars
 perplexus dot info

 9 random digits (Posted on 2003-05-02)
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)?

 See The Solution Submitted by Gamer Rating: 3.4000 (5 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
 Array Solution | Comment 15 of 20 |
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
this value

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 ..>
else
<.. 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

 Search: Search body:
Forums (0)