Want to produce random numbers between 1-45 without repetition

前端 未结 4 1430
你的背包
你的背包 2021-01-29 13:53

I have come across a very strange problem. I have tried to find its solution but in vain. My problem is that I want to create a random number between 1-45 and I don\'t want tha

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-29 14:24

    What you really want is to create a set of numbers in a given range and to randomly remove one of the numbers until the set is empty.

    Here is a function which generates another function which does exactly that:

    function generateRandomRangeSet(beg, end) {
      var numbers = []; // Create an array in range [beg, end].
      for (var i=beg; i<=end; i++) { numbers.push(i); }
      return function() {
        if (numbers.length < 1) { throw new Error('no more numbers'); }
        var i=Math.floor(Math.random()*numbers.length), number=numbers[i];
        numbers.splice(i, 1); // Return and remove a random element of the array.
        return number;
      }
    }
    
    var r = generateRandomRangeSet(1, 45);
    r(); // => 9
    r(); // => 24
    r(); // => 7 ... for each number [1, 45] then ...
    r(); // Error: no more numbers
    

提交回复
热议问题