0

I am making a function that will generate a unique 'x' numbers base on the range & set given.

Examples

  • randomizer({ range: 50, set: 5 }) = [8, 16, 32, 40, 48]
  • randomizer({ range: 15, set: 3 }) = [4, 11, 15]
  • randomizer() = [2, 4, 5, 3, 1]

      function randomizer(data) {
          const dataRange = data && data.range
              ? data.range
              : 5;
          const dataSet = data && data.set
              ? data.set
              : 5;
    
          if (dataRange < dataSet) {
              console.log('Range cannot be lower than the Set!');
              return;
          }
    
          const randomizerRange = [];
          for (let r = 1; r <= dataRange; r++) {
              randomizerRange.push(r);
          }
    
          const randomizerSet = [];
          let randomNumber;
          for (let s = 1; s <= dataSet; s++) {
              randomNumber = Math.floor((Math.random() * (dataRange - s)) + 1);
              if (randomizerSet.includes(randomizerRange[randomNumber])) {
    
                  /*
                  make sure that the next number on randomizerSet is unique
                  this loop is crashing the browser 
                  */
                  let isUnique = false;
                  do {
                      randomNumber = Math.floor((Math.random() * (dataRange - s)) + 1);
                      if (!randomizerSet.includes(randomizerRange[randomNumber])) {
                          isUnique = true;
                      }
                  } while (!isUnique);
    
              }
              randomizerSet.push(randomizerRange[randomNumber]);
          }
    
          return randomizerSet;
      }

My issue is on the while loop, the browser is crashing
I need help to make sure that the returned array will never have a repeated value? Thank you.

Neo Genesis
  • 922
  • 11
  • 26
  • This is a horrible way to do it. Make an array with all the numbers in the range. Shuffle the array. Return the first N elements. – Barmar Jan 28 '21 at 18:56
  • Is it looping too many times? I personally don't use a lot of while loops because to me for loops are easier to control – Other Me Jan 28 '21 at 18:57
  • I think your problem is the includes... You have to use it like this: `array.includes(THE_VALUE_YOU_ARE_LOOKING_FOR)`. What you are doing is to check with the index which will lead in an always false which will get you stuck inside the array. I created my own version of this with the includes (you can check there how I did it): https://jsfiddle.net/q0bc3x6z/ Good luck with your project ;) – Lars Flieger Jan 28 '21 at 19:53

0 Answers0