I\'m new to javascript and trying to get comfy with Functions
, For
loops, and If
statements. I\'m working on a simple exercise that genera
There are many ways to solve this problem. I am contributing my way of solving it.
function randoNumbers(min, max) {
let randomNumbers = [];
for (; randomNumbers.length < 5;) {
const value = Math.floor(Math.random() * (max - min) + +min);
if (!randomNumbers.includes(value))
randomNumbers.push(value);
}
console.log(randomNumbers);
}
randoNumbers(1, 10);
A very plain solution would be to generate numbers until the generated number is not already included in the array, and then push it to the result array:
function randoNumbers(min, max) {
const randomNumbers = [];
for (let counter = 0; counter < 5; counter++) {
let num;
do {
num = Math.floor(Math.random() * (max - min) + min);
}
while (randomNumbers.includes(num))
randomNumbers.push(num);
}
console.log(randomNumbers);
}
randoNumbers(1, 10);
For slightly better complexity, you could use a Set
instead (set.has
is quicker than arr.includes
):
function randoNumbers(min, max) {
const set = new Set();
for (let counter = 0; counter < 5; counter++) {
let num;
do {
num = Math.floor(Math.random() * (max - min) + min);
}
while (set.has(num))
set.add(num);
}
console.log([...set]);
}
randoNumbers(1, 10);