Place a do ... while
statement on your random generation that check if the number was already on the loto numbers.
function lotoGenerator() {
var array = [];
var i;
for (i = 0; i <=6; i++) {
do {
// Generate your random number
var temp = Math.floor((Math.random() * 39) + 1);
// If the number already exists, the index of it on loto array will be different of -1, so it already exists
var alreadyExists = array.indexOf(temp) !== -1;
} while (alreadyExists) // Repeat this many times necessary to get an unique number.
array.push(temp);
}
console.log(array);
}
lotoGenerator();
Note that this isn't the most efficient solution since you can have the bad luck of having the same number sorted many times, so the do...while
loop may run too many times.
The best way to solve this is by having an array with available numbers and removing the drawn number:
function lotoGenerator() {
var available = [];
var drawn = [];
for (var i = 1; i<= 40; i++) {
available.push(i);
}
for (i = 0; i <=6; i++) {
var random = Math.floor((Math.random() * available.length));
drawn.push(available[random]);
available.splice(random, 1);
}
return drawn;
}
This second function have an well known execution time, and will be more efficient as the number of random elements increase.