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

Home > Algorithms
9 random digits (Posted on 2003-05-02) Difficulty: 3 of 5
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
Please log in:
Login:
Password:
Remember me:
Sign up! | Forgot password


Search:
Search body:
Forums (0)
Newest Problems
Random Problem
FAQ | About This Site
Site Statistics
New Comments (3)
Unsolved Problems
Top Rated Problems
This month's top
Most Commented On

Chatterbox:
Copyright © 2002 - 2024 by Animus Pactum Consulting. All rights reserved. Privacy Information