lundi 7 octobre 2019

How to get a certain number of unique random numbers in a certain range?

I have a function that takes user input to tell it how many random numbers to output, and the range to make the random numbers between (say 1-90). The problem is that it will give repeat numbers, but I want only unique numbers. Does anyone know how I can change the code to achieve this?

function random() {
    let randomNums = [];
    let numBox = document.querySelector('.numBox').value;
    let highestNumber = document.querySelector('.highestNumber').value;

    for (let i = 0; i < numBox; i++) {
        let num = Math.floor(Math.random() * highestNumber) + 1;
        randomNums.push(` ${num}`)  
    }     
    randomNums.sort(function(a, b) {return a - b;});
    document.querySelector('.randomOutput').innerHTML = randomNums;
}



Aucun commentaire:

Enregistrer un commentaire