If I only focus on the question title.
Adding random numbers to an array and then checking if there are repetitions before printing array
Aside the "assumed" use case where the suggested duplicate about "shuffling an existing array" would be quite good. If you want to create an array of unique numbers having an amount
length of values between a min
and a max
, Here is how:
function getArrayOfuniqueRandomNumbers(min, max, amount) {
let result = [];
if (amount !== undefined && amount < max - min) {
while (result.length < amount) {
let randomNumber = Math.floor(Math.random() * (max - min));
if (result.indexOf(randomNumber) == -1) {
result.push(randomNumber);
}
}
}
return result;
}
// So here, you request an array of 20 numbers between 0 and 30
console.log(getArrayOfuniqueRandomNumbers(0,30,20))
The function will return a non-empty array if the requested amount
is possible given the min
and max
.
There is a condition to avoid an infinite loop of the while
. So if the provided arguments do not allow to find the required amount of unique numbers, it will return an empty array.
How it works:
while
the amount
is not reached, keep on trying to add a new random number.
The numbers are added to the array to be returned only if not already present because of the .indexOf()
check.
Do whatever you wish with the returned array.