Search code examples
javascriptcanvasrandomslicesplice

Javascript - Multiple Unequal Random Number Generator


I am trying to write a function which produces four unequal random numbers in a given range, but the function is currently failing at the while (selection[i] in selection.slice().splice(i) line. This line should check whether the current (i'th) value is shared by any of the other random values but at the moment it seems to do nothing - perhaps I have used in incorrectly? Any help would be appreciated.

function contains(a, obj) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] === obj) {
    return true;
    }
  }
  return false;
}

selected=[];

function randomSelection() {

  var notselected=[];
  for (var i=0; i<25; i++) {
    if(!contains(selected, i)) {
        notselected.push(i);
    }
  }
  var selection=[notselected[Math.floor(Math.random() * notselected.length)],
                             notselected[Math.floor(Math.random() * notselected.length)],
                             notselected[Math.floor(Math.random() * notselected.length)],
                             notselected[Math.floor(Math.random() * notselected.length)]];

  for (var i=0; i<selection.length; i++) {
    while (selection[i] in selection.slice().splice(i)) {
      alert('Hello!')
      selection[i] = notselected[Math.floor(Math.random() * notselected.length)];
    }
  }
  for (var i=0; i<selection.length; i++) {
    selected.pop(selection[i]);
  }
}

Solution

  • You can obtain a random value between two numbers using the following method

    function getRandomArbitrary(min, max) {
       return Math.floor(Math.random() * (max - min)) + min;
    }
    

    If the value needs to be an integer you can use the following method:

    function getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min)) + min;
    }
    

    So, supposing that you need 4 different random integer values you could do something like that

    var randoms = [];
    while(randoms.length < 4) {
    
      var random = getRandomInt(0, 25);
    
      if(randoms.indexOf(random) === -1) {
        randoms.push(random);
      }
    }