mardi 25 avril 2017

Javascript - Multiple, Unequal Random Numbers

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]);
  }
}




Aucun commentaire:

Enregistrer un commentaire