generating a random number without repetitions

Federico Source

I am trying to generate a series of random numbers generating every time a different one, I came up with a simple function in javascript but it still gives me the same number consecutively and I fail to understand why, can anyone help me please

function random(){
  var randNum;
  var prevnumb;
  do{
    randNum = Math.floor(Math.random() * quotes.length);
  } while(prevnumb == randNum);
  prevnumb = randNum;
  return randNum;
}
javascriptloopsrandom

Answers

answered 5 months ago Joschi #1

You have to pass the previous number to your function, and I would recommend passing the highest desired random number as well. Do not use floor() or you will never get a random 0. If you find it convenient, you create a parameterless function handling this like

function randomizer(max) {
  var prevNum;
  return function() {
    var randNum;
    if (!max) return 0;
    while (1) {
      randNum = parseInt(Math.random() * (max + 1));
      if (prevNum !== randNum) {
        break;
      }
    }
    prevNum = randNum;
    return randNum;
  }
}

var last;
var rnd = randomizer(2);
for (var i = 0; i < 100; i++) {
  var cur = rnd();
  console.info("difference ", last - cur, " is not 0");
  last = cur;
}

answered 5 months ago Selvarani #2

You can store previous value into an array and you can validate,

function random(){
  var randNum;
  randNum = Math.floor(Math.random() * quotes.length);
  if(!prevnumb.contains(randNum)){
  prevnumb.push(randNum);
  } 
  return randNum;
}

comments powered by Disqus