skip to Main Content

Using NodeJS 14. I have a script that needs to generate 10,000 unique numbers between 1 and 10000. i have a function that takes 1 as min and 10000 as max. When I run it, only ~7000 are unique the rest are duplicates. I understand that not all 10k would be unique, but 30%? What can I do to get more of then unique?

function is:

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

sorted sample
1856
1871
1873
1879
1879
1885
1895
1903
1911
1911

2

Answers


  1. To obtain exactly 10000 unique random numbers, you can just shuffle all the integers from 1 to 10000.

    let nums = Array.from({length:10000}, (_, i) => i + 1);
    for (let i = nums.length - 1; i > 0; i--) {
      const j = Math.random() * (i + 1) | 0;
      [nums[i], nums[j]] = [nums[j], nums[i]];
    }
    console.log(nums);
    Login or Signup to reply.
  2. You can loop through the size of the set an keep pushing into it until the size if your desired size. Set guarantees uniquness.

    const uniqueNumbers = new Set(); 
    
    while (uniqueNumbers.size < 10000) { 
      let randomNum = Math.floor(Math.random() * 10000) + 1; 
      uniqueNumbers.add(randomNum); 
    }
    
    //set to array
    console.log([...uniqueNumbers]);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search