We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'm creating an audio player that plays random samples from an array. How do I make sure it doesn't play the same one twice in a row?
How can I tell the random function not to generate the last random number?
Answers
Try using a physical metaphor to think this through.
"How can I ensure that a random die never rolls the same number twice in a row?"
You can't. That's what it means for it to be random -- each outcome has a probability.
But imagine a deck of cards. You can put them in an order, then hand them out, and that ensures that no two people get the Ace of Spades.
That's called "shuffling."
See for example IntList.shuffle():
The other way is to keep track of the last random number, and re-roll if it matches.
Try it:
...example output:
Thanks. I thought about rerolling but I got an error saying the variable may not have been initialized (because if I called it in the function it would stay constant). Your example pointed out that it should be in setup so it's initialized and then updated in the function.
Thank you!