title: Javascript: generate random numbers in range, avoiding previous two
body: <p>I'm creating a slider with 6 slides, and I want to randomly move between them, making sure that neither of the previous two slides are shown as the next slide. The functionality doesn't really matter, since what I'm really doing is generating random numbers and keeping track of the previous two. The first slide is always numbered 1, so for the first two iterations that'll be one of the previous numbers that can't be used.</p>
  
  <p>Here's what I have so far, and it works fine for generating the random numbers in the range, but 'caching' the last two values doesn't work reliably:</p>
  
  <pre><code>        var rand = Math.floor(Math.random() * 6) + 1;
          var prev1 = 1;
          var prev2;
  
          function randomSlide() {
              // 5 second interval between slides
              // Don't show either of previous two slides next
              random = setInterval(function() {
                  prev2 = prev1;
                  prev1 = rand;
  
                  do {
                      rand = Math.floor(Math.random() * 6) + 1;
                  } while (rand == prev1 || rand == prev2);
  
                  prev1 = rand;
  
                  $('#slider').anythingSlider(rand);
  
                  //console.log(prev1,prev2);
  
  
              }, 5000);
          }
          function firstSlide() {
              firstTime = setTimeout(function() {
                  randomSlide();
              }, 5000);
          }
  
          firstSlide();            
          randomSlide();
  </code></pre>
  
  <p>It's quite simple I think but my brain's getting frazzled trying to parse the values of the two 'cache' variables at the first, and then each subsequent, iteration.</p>
  
  <p>I'm executing a single iteration at the beginning because if randomSlide() executes on load then the first (welcome) slide doesn't get a chance to display.</p>