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)?
Assuming I am given random(), the main() would be:
main(){
int digits[9], number, digitnum, answer[9], count;
for(digitnum=1;digitnum<=9;digit+=1){digits[digitnum]=digitnum;}
for(digitnum=1;digitnum<=9;digit+=1){
number=random(10-digitnum);
answer[digitnum]=digits[number]
for(count=1;count<=9;count+=1){
if (count>=(10-digitnum) digits[count]=0;
else if(count>=number) digits[count]=digits[count+1]
}
}
for (count=1;count<=9;count+=1){ cout << answer[count];}
All this is doing is creating a number 123456789, then picking a digit from that as the next digit. Then it takes out that digit and pushes everything down one, and replaces any old number spots with 0. Then it prints the number.
For example: (Using 5 digits)
Random(?) - Old:12345 New:
Random(5) 3 Old:12450 New: 3
Random(4) 1 Old:24500 New: 31
Random(3) 2 Old:25000 New: 314
Random(2) 2 Old:20000 New: 3145
Random(1) 1 Old:00000 New: 31452
|
Posted by Gamer
on 2003-05-02 11:10:16 |