dimanche 20 décembre 2015

How to generate 10 unique random numbers from a set of 100 using javascript?

I'm working on a minesweeper web app and i am trying to generate 10 mines with unique location id's (1-100). I wrote a function to do this, and log the 10 numbers to an array called numbers. But every time I run the program it produces 10 identical numbers from 1-100. Does anyone know what I did wrong? (Update: It worked when I changed the loop from while to do...while but the question now is why did that fix it?)

Here is my jQuery code:

var chooseMines = function(num) {
  var temp,bool,numbers = [];
  for(i = 1; i <= 10; i++) {
    do
    {
        bool = 0;
        temp = Math.floor(100 * Math.random()) + 1;
        for(j = 0; j < numbers.length; j++) {
            if(numbers[j] === temp)
            {
                bool = 1;
            }
        }
    } while(bool)
    numbers.push(temp);
}
window.confirm(numbers);
return numbers;
};




Aucun commentaire:

Enregistrer un commentaire