Sunday, July 12, 2009

(C++) Can i stop numbers from appering in the rand() funcation?

i have a random number genartor that loops gening numbers can i make it so that once a number is used it cant come up again? until the number range is empty like bewteen 1 and 100 if 23 comes up it cant come up again. would i have to use an array? i suck with arrays lol

(C++) Can i stop numbers from appering in the rand() funcation?
Why not just create an array of numbers 1 to 100 and "shuffle them" randomly using the random number generator. Starting at 1 pick a number between 1 and 100, if it is say 52, stick 1 in index 52 and 52 in 1 (swap), then pick a number between 2 and 100, swap, then 3 and 100, swap, and so on up to 99.





Now, all your numbers are shuffled and you just pop them of the front of the array as you need them. Reshuffle when it is empty.
Reply:Yeah, I think the easiest way to do it would just be to create an array but it shouldn't be that hard. Just create an array of size 100 and then put in each number you get from the RNG. Every time you get a new number just go through the array and check to see if your new number is already in there.

quince

No comments:

Post a Comment