Reputation: 59
I'm in the early stages of learning JavaScript and I had thought of making a lottery number generator for practice. This is what I have so far (z is for the total lottery balls, and y for the number of digits to be generated):
function generateRandomNumbers(z,y){
var resultArray = [];
var output = "";
if(isNaN(z) || isNaN(y)){
return "You have entered an invalid value";
}else{
for(x=0; x<y; x++){
var result = Math.ceil(Math.random()*z);
resultArray.push(result);
output += resultArray[x]+ "\n";
}
}
return output;
}
The problem is, this doesn't prevent duplicates from occurring. What could be a good way to ensure that the array's content doesn't contain any duplicates? I apologize if this has already been asked before.
Upvotes: 2
Views: 1529
Reputation: 9813
As its lottery, the possible numbers are contiguous. You can create a list that holds all possible number, then use .splice to take one from them each time, until you take enough numbers:
function generateRandomNumbers(z,y){
// You can't take more, or you can set y = z;
if (y > z) {
return [];
}
var numbers = [];
var result = [];
var i;
// Create list.
for (i = 1; i <= z; ++i) {
numbers.push(i);
}
var random;
// Take a random number from list each time.
for (i = 0; i < y; ++i) {
random = Math.floor(Math.random() * z);
// Put the randomly take number into result.
result.push(numbers.splice(random, 1)[0]);
// As we take one number from the list, remember to decrease the possible range by 1.
--z;
}
return result;
// If you want a string form
// return result.join('\n');
}
console.log(generateRandomNumbers(49, 6))
Upvotes: 2
Reputation: 4997
You can test if the number that was just generated is already in resultArray
.
If so, then just try to loop again for this number
for(var x = 0 ; x < y ; x++){
var result = Math.ceil(Math.random()*z);
if (resultArray.indexOf(result) > -1){
x--;
}
else{
resultArray.push(result);
}
}
return resultArray.join("\n");
Also you have to check for y <= z
because you can't generate more unique numbers than the range [0 - [z
.
Upvotes: 0
Reputation: 1436
I suggest using jQuery...
var uniqueNum= [];
$.each(num, function(i, el){
if($.inArray(el, uniqueNum) == -1)
uniqueNum.push(el);
});
nice and easy =]
Upvotes: 0