Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple for loop does not seem work properly

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);
like image 445
Kay. T Avatar asked Dec 25 '19 05:12

Kay. T


2 Answers

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!

like image 173
Raghu Chahar Avatar answered Oct 12 '22 02:10

Raghu Chahar


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?

like image 44
Xixiaxixi Avatar answered Oct 12 '22 03:10

Xixiaxixi