Go Down

Topic: Random() (Read 1 time) previous topic - next topic

iluvplanes

I have a project, in which i need to choose between 4 numbers.
I used random(2,5) because those were the values I need.
However, i need to make sure each return is different.
Ex. I can't have the same number repeat. How do I do this?

Shmaron

keep track of the most recent random number. Then before allowing a new random number, compare it to the variable. If it's different, do what you need to do with it. If it's the same, keep generating new ones until it's different.

Lather, rinse, repeat.

Nick Gammon


Ex. I can't have the same number repeat. How do I do this?



You want a shuffle algorithm. Put the four numbers into an array. Pick one at random. Remove that. Pick one of the remaining three at random. Remove that. Pick one of the remaining two at random. Then you have the last one.

iluvplanes

Nick, Docedison, Shmaron, Thanks for the replies! I'll try Nick's out soon.

Nick Gammon


Go Up