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.)
Solution solution | Comment 1 of 20
A) For the fewest invocations of random(), start with two strings: one of zero length and the other of length containing the digits 1 to 9 where order doesn't matter.

Then invoke random() 8 times starting with a parameter of 9, and ending with a parameter of 2. Each time, use its output to pick a character from the string that started full, and place it at the end of the string that started empty. After this there will be 1 character left in the originally-full string. Transfer that to the end of the almost-built string, which now has 9 digits and can be converted to a number by ordinary conversion processes.

DECLARE FUNCTION randm& (n&)
DEFLNG A-Z
RANDOMIZE TIMER

FOR trial = 1 TO 5
  source$ = "123456789"
  result$ = ""
  FOR i = 9 TO 2 STEP -1
    p = randm(i) ' random is a keyword in this language so using randm
    result$ = result$ + MID$(source$, p, 1)
    source$ = LEFT$(source$, p - 1) + MID$(source$, p + 1)
  NEXT
  result$ = result$ + source$' now the last character
  n = VAL(result$)
  PRINT n
NEXT trial

END

FUNCTION randm (n)
  randm = INT(RND(1) * n + 1)
END FUNCTION

One run of the above (as it is set to give 5 examples) is:

786591324
281735694
928641357
478325619
784592316

B) Oh, I've already done that in A. Maybe you expected A to be to keep calling random() with a parameter of 1,000,000,000, until you get a result that was nine digits, all different and then stop. Or perhaps you had in mind calling random(9) as many times for each digit until it produced a digit different from any that you had previously. In any case the solution for B is my above solution for A.
  Posted by Charlie on 2003-05-02 08:11:19
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 (7)
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