If I want 4 random number in an array [num1, num2, num3, num4], I can't do
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
const arr = [getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10)]
because I'll have duplicated value. Is there any way or library that allow me to generate a unique set of randomed number?
You can declare the array as empty and then continue adding values to it until it has 4 numbers. You can also avoid duplicates by using if condition.
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
var arr=[];
var min=1, max=10;
while (arr.length != 4) // executes loop till length of array is 4
{
var i = getRandomFloat(min, max);
// checking if number already exists in array
if (arr.includes(i))
{
continue;
}
arr.push(i);
}
This is efficient method to achieve this. You can use Set to get the random unique numbers in an array
You can even add a check if unique numbers are possible or not as
if (max - min < n) return "Not possible";
function getRandomNumbers(n, min = 0, max = 0) {
const set = new Set();
while (set.size !== n) {
set.add(Math.random() * (max - min) + min);
}
return [...set];
}
console.log(getRandomNumbers(4, 1, 10));