I'm having a trouble to get an array with numbers from 1 to 16 randomly without repetition. I made num array to put numbers from createNum function.
The createNum function has a for loop which gets numbers from 1 to 16 until if statement push 16 numbers into num array.
At the end, I run createNum() and display numbers on the web. While I'm making this code it sometimes worked but now it's not working.
can somebody point out where I made mistakes?
let num = [];
function createNum () {
for (i = 0; i <= 15;) {
let numGen = Math.floor(Math.random() * 15) + 1;
if (!num.includes(numGen)) {
num.push(numGen);
i++;
};
};
}
console.log(createNum());
document.getElementById("selectedNumbersShownHere").innerHTML = num;
console.log(num);
This is because Math.random()
never returns 1, so at the end Math.floor(Math.random() * 15)
will returns maximum 14 and adding it to 1 will get you maximum 15.
Use Math.ceil
instead of Math.floor
i.e
let num = [];
function createNum () {
for (i = 0; i <=15;) {
let numGen = Math.ceil(Math.random() * 16);
console.log(numGen)
if (!num.includes(numGen)) {
num.push(numGen);
i++;
};
};
}
console.log(createNum());
document.getElementById("selectedNumbersShownHere").innerHTML = num;
console.log(num);
Hope it helps!
for (i = 0; i <= 15;)
generates 16 numbers, but Math.floor(Math.random() * 15) + 1
only have 15 possible values (1~15).
A shuffle
function is recommended. Your function would be slow if you generate a large size shuffled array.
How can I shuffle an array?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With