-1

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?

Ambrose
  • 11
  • 1
  • 1
    Does this answer your question? [Generate unique random numbers between 1 and 100](https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100) – poPaTheGuru Sep 21 '21 at 04:41
  • No, you won't have duplicated value. Did you try running your code yourself once? – Kishan Kumar Sep 21 '21 at 04:42
  • @KishanKumar really? have you tried running the code *more than once* – Bravo Sep 21 '21 at 04:43
  • Yes, I did @Bravo – Kishan Kumar Sep 21 '21 at 04:45
  • @KishanKumar - do you think it's at all possible (though highly unlikely) to get the same random number more than once - but I do see your point - didn't realise the numbers were FLOATS rather than integers :p – Bravo Sep 21 '21 at 04:52
  • @Bravo, that would be totally possible to get the same random number, I don't disagree with that. But I don't see the case here, as I did try running it about 4-5 times to see if I missed anything. – Kishan Kumar Sep 21 '21 at 05:41

2 Answers2

0

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);
    }
Huzaifa Farooq
  • 116
  • 1
  • 10
0

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));
DecPK
  • 24,537
  • 6
  • 26
  • 42