Pedro Arévalo
Pedro Arévalo

Reputation: 1

How can I make an array of random numbers in a range without repeating numbers using a Do... while loop?

I'm creating a random number generator in JavaScript for lotto numbers. This numbers must be in a range of 1 - 50 and then sort them from smallest to largest. I already managed to do that using a do while loop but now I'm having some trouble for the repeated numbers.

I tried an If statement for compare the new number with the previous one, but the code is not working properly and the numbers are repeating

Here is my code block


const randomNumber = (minRange, maxRange) => {
    return Math.floor(Math.random() * (maxRange - minRange + 1) + minRange);
};

// numbers added in order in lottoNumbers array
let lottoNumbers = [];
let num = 0;

do {
    num = randomNumber(1, 50);
    lottoNumbers.push(num);
    if(!lottoNumbers.includes(num)) {
        lottoNumbers.push(num);
    }
    lottoNumbers.sort(function(a, b) {return a - b});
} while (lottoNumbers.length < 5);

Upvotes: 0

Views: 803

Answers (1)

gog
gog

Reputation: 11347

You can use a Set for that

const randomNumber = (minRange, maxRange) => {
    return Math.floor(Math.random() * (maxRange - minRange + 1) + minRange);
};


let ns = new Set()

while (ns.size < 6)
    ns.add(randomNumber(1, 50))

let result = [...ns].sort((a, b) => a - b)

console.log(...result)

Upvotes: 0

Related Questions