i would like to generate random numbers from 1-50, then exclude an array like; 4,7,10,20,35 etc
i tried this;
let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];
if (!exclNum.includes(mainNum)) {
console.log(Math.floor(Math.random() * mainNum) + 1)
}
but it still generates numbers that's still in the array, please is there anything i am missing?
Thanks for your response in advance
You need to generate the random number first, then check if it's in the array. Do this in a loop until it's not in the array.
let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];
let ranNum;
while (true) {
ranNum = Math.floor(Math.random() * mainNum) + 1;
if (!exclNum.includes(ranNum)) {
break;
}
}
console.log(ranNum);
You are currently checking whether exclNum includes mainNum, which is 50.
Instead, generate the random number and check whether exclNum includes it:
let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];
while(!exclNum.includes((randomNum = Math.floor(Math.random() * mainNum) + 1))){
console.log(randomNum)
break;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
A do... while loop is more concise
function myRandom(mainNum, exclude) {
let r;
do {
r = Math.floor(Math.random() * mainNum) + 1;
} while(exclude.includes(r))
return r;
}
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));