Reputation: 151
I'm trying to create a random Non-Repeating Number Generator for numbers up to 13. When I run the following function I get varying out puts, here are the results of running the function 5 times using a button click, and the code. I can't understand why it's repeating some numbers.
var checkIfRandom = new Array();
function getRandom(){
var randomNum= Math.floor(Math.random()*13);
if(checkIfRandom.indexOf(randomNum) !== -1){
getRandom();
}else if(checkIfRandom.indexOf(randomNum)==-1){
checkIfRandom.push(randomNum);
}
console.log(randomNum);
};
//results
2 //Click 1
7, 2 //Click 2
6 //Click 3
1 //Click 4
5,7,1 //Click 5
[2, 7, 6, 1, 5]//After 5 clicks I logged the checkIfRandom array to the console in chrome.
Upvotes: 1
Views: 54
Reputation: 5821
// empty array with size we want
var randomList = new Array(13).join("|").split("|");
function getRandom()
{
// if "" doesn't exist then every number has been used
if(randomList.indexOf("") === -1) return -1;
// get random number
var randomNum = Math.floor(Math.random() * randomList.length);
// if its already used then get a new one
if(randomList[randomNum]) return getRandom();
// save the random num and return it
randomList[randomNum] = true;
return randomNum;
}
Upvotes: 0
Reputation: 309
You're using recursion, which means it's storing the previous, non-unique numbers in the stack and is still logging them. Move the console.log()
into the else if
so it reads:
function getRandom(){
var randomNum= Math.floor(Math.random()*13);
if(checkIfRandom.indexOf(randomNum) !== -1){
getRandom();
}else if(checkIfRandom.indexOf(randomNum)==-1){
checkIfRandom.push(randomNum);
console.log(randomNum);
}
};
Upvotes: 1