Generate Unique Numbers in Array

前端 未结 2 1087
忘掉有多难
忘掉有多难 2021-01-26 03:56

I\'m new to javascript and trying to get comfy with Functions, For loops, and If statements. I\'m working on a simple exercise that genera

相关标签:
2条回答
  • 2021-01-26 04:41

    There are many ways to solve this problem. I am contributing my way of solving it.

    function randoNumbers(min, max) {
    
      let randomNumbers = [];
    
      for (; randomNumbers.length < 5;) {
        const value = Math.floor(Math.random() * (max - min) + +min);
        if (!randomNumbers.includes(value))
          randomNumbers.push(value);
      }
      console.log(randomNumbers);
    
    }
    
    
    
    randoNumbers(1, 10);

    0 讨论(0)
  • 2021-01-26 04:42

    A very plain solution would be to generate numbers until the generated number is not already included in the array, and then push it to the result array:

    function randoNumbers(min, max) {
      const randomNumbers = [];
      for (let counter = 0; counter < 5; counter++) {
        let num;
        do {
          num = Math.floor(Math.random() * (max - min) + min);
        }
        while (randomNumbers.includes(num))
        randomNumbers.push(num);
      }
      console.log(randomNumbers);
    }
    
    randoNumbers(1, 10);

    For slightly better complexity, you could use a Set instead (set.has is quicker than arr.includes):

    function randoNumbers(min, max) {
      const set = new Set();
      for (let counter = 0; counter < 5; counter++) {
        let num;
        do {
          num = Math.floor(Math.random() * (max - min) + min);
        }
        while (set.has(num))
        set.add(num);
      }
      console.log([...set]);
    }
    
    randoNumbers(1, 10);

    0 讨论(0)
提交回复
热议问题