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)?
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 originallyfull string. Transfer that to the end of the almostbuilt string, which now has 9 digits and can be converted to a number by ordinary conversion processes.
DECLARE FUNCTION randm& (n&)
DEFLNG AZ
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 20030502 08:11:19 