Exclude last generated random number?

edited November 2017 in How To...

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?

Tagged:

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:

    int lastNum;
    int newNum;
    void setup(){
      frameRate(4);
    }
    void draw(){
      while(newNum == lastNum){
        newNum = (int)random(1,7);
      }
      print(newNum + " ");
      lastNum = newNum; 
    }
    

    ...example output:

    6 3 4 5 6 3 6 2 4 6 2 5 3 5 6 2 3 4 5 2 1 4 1 2 4 2 6 3 2 3 2 6 3 2 5 3 6 1 3 2 6 2 3 2 4 3 6 3 2 4 1 4 5 3 6 4 5 2 4 6 3 6 5 4 3 2 6 4 1 3 2 1 5 4 2 1 6 2 5 1 6 2 3 5 3 5 2 4 1 5 3 6 1 6 3 5 3 1 3 6 3 2 4 1 2 6 3 4 6 2 4 5 6 2 1 2 1 3 2 3 6 2 5 6 4 2 4 3 2 1 5 2 4 2 4 5 2 6 3 1 4 6 4 1 6 2 5 4 3 5 6 2 3 4 3 1 4 6 1 6 4 2 3 1 4 2 3 2 1 4 2 3 6 5 4 2 6 5 1 4 5 3 2 3 2 3 4 1 2 1 3 1 6 4 5 1 2 6 2 5 6 5 2 6 2 6 2 6 5 4 3 1 6 5 1 6 2 1 4 2

  • 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!

Sign In or Register to comment.