I try to output randomly some numbers from an array of possible values.
The problem that I have is with the recursion, so that my function checking if the number generated randomly was already used before starts again if the number was already used (and is not in the array of possible values anymore).
I get an infinite loop which I also don't understand.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// Global array of possible numbers
var possibleNumbers = [1, 2, 3, 4];
// Check if element in the array
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
// Random number between 1 and 4
function genRand(){return Math.floor(1+ (4 * Math.random()));}
// Return an random number from the possible numbers in the global array
function randNumFromArray() {
var generatedNum = genRand();
console.log('possibleNumbers so far:' + possibleNumbers);
console.log('generatedNum: ' + generatedNum);
// Restart as long as the number is not in the array (not already used)
while(inArray(generatedNum,possibleNumbers) === false) {
console.log('Generating again...');
randNumFromArray();
}
console.log('generatedNum not used yet, using it');
// Use that number and remove it from the array
var index = possibleNumbers.indexOf(generatedNum);
if (index > -1) {
possibleNumbers.splice(index, 1);
}
console.log('Removing the number from the array');
console.log('possibleNumbers after removal:' + possibleNumbers);
return generatedNum;
}
// Calling the function 4 times to get the 4 possible numbers in a random order
randNumFromArray();
randNumFromArray();
randNumFromArray();
randNumFromArray();
</script>
</head>
<body>
</body>
</html>