How to generate unique random numbers

Viewed 362

I’m trying to generate 5 unique random numbers between two numbers. The sixth number is a random number between another set of numbers but it doesn’t have to be unique. I tried to ensure the uniqueness of each number by placing the first randomly generated number in an array.

Then each subsequent randomly generated number is checked against the numbers in this array. Any generated number matching a number in the array will be discarded and a new one is generated until one that doesn’t match any in the array is is found. My code doesn’t work because occasionally it produces duplicates.

How is this fixed?

https://jsfiddle.net/L3h0rf5q/

 var btnGen = document.getElementById('generate');
      var fiveNum = document.getElementById('fiveNums');
      var lastNum = document.getElementById('lastNum');

      btnGen.addEventListener('click', function () {
        
        let ranNum;
        
        let firstFive = "";
        let pb = "";
        let oldNum;

        ranNum = GenerateNumbers();

        ranNum.sort(
          (a, b) => {
             if (a < b) {
                 return -1;
             }
             if (a > b) {
              return 1;
               }
             return 0;
             }
         );

         for(let i=0; i<ranNum.length; i++){
           if(i<ranNum.length - 1){

            
               if(ranNum[i].toString().length<2){
                  firstFive += "0" + ranNum[i].toString() + "&nbsp;" + "&nbsp;" + "&nbsp;" + "&nbsp;" + "&nbsp;" + "&nbsp;"
               }else{
                  firstFive += ranNum[i].toString() + "&nbsp;" + "&nbsp;" + "&nbsp;" + "&nbsp;" + "&nbsp;" + "&nbsp;"
               }


           }else{
               if(ranNum[i].toString().length<2){
                  pb = "0" + ranNum[i].toString();
               }else {      
                  pb = ranNum[i].toString(); 
               }

         }

         fiveNum.innerHTML = firstFive;
         lastNum.innerHTML = pb;
         }
        
      });

      function GenerateNumbers() {
        let randomNums = [];
        let selectedNums = [];        
        let newNum = undefined;
        for (let i = 0; i < 6; i++) {

          if (i == 0) {
              newNum = Math.floor(Math.random() * 75) + 1              
              randomNums[i] = newNum;
              selectedNums.push(newNum);
              
          } 
          if (i >0  && i < 5){            
                         
              while (selectedNums.includes(newNum)) {                
                newNum = Math.floor(Math.random() * 75) + 1
              } 
              
              randomNums[i] = newNum;
              //add to an array
              selectedNums.push(newNum);
            
          } 
          if (i == 5) {
            randomNums[i] = Math.floor(Math.random() * 42) + 1
          }
        }      
               
        return randomNums;
      }
<div style="margin-left:20%; width:500px; font-weight:bold; font-size:30px;">

    <button id="generate" style="margin-left:36%">Generate Numbers</button>
    <br><br>
    <div>
      <label style="margin-left:20%">Generate Numbers</label>
      <br>
      <div style="background-color:black">
        <span id="fiveNums" style="margin-left: 10%; width:80%; color:blue;"></span>
        <span id="lastNum" style="color:blue;"></span>
      </div>
    </div>

1 Answers

the approach is to make an array with all possible values, shuffle it, and then grab 5 of them (and for that extra value you want, just calculate it separately). you can do this with plain javascript if you want:

function shuffle(arr) {
  let i = arr.length;
  while(i != 0) {
    let j = Math.floor(Math.random() * i--);
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

//fill arr with all possible values
var arr = [];
for(var i = 50; i <= 100; i++) arr.push(i);

//shuffle
shuffle(arr);

//grab 5
console.log(arr.slice(-5));

//and the extra one
console.log(Math.floor(Math.random() * 76) + 75);

But doing it with rando.js is a lot nicer:

console.log(randoSequence(50, 100).slice(-5));//first five
console.log(rando(75, 150));//the other one
<script src="https://randojs.com/2.0.0.js"></script>

Related