select random value NOT in array

后端 未结 5 936
渐次进展
渐次进展 2021-01-20 07:56

How would I select a random value (0 to 30) that is not in this array?

var list = new Array(1,3,4,7,8,9);
相关标签:
5条回答
  • 2021-01-20 08:07

    A little recursive function:

    getNum() {
      let randomNum = Math.floor(Math.random() * (30 - 1)) + 1
      if (list.includes(randomNum)) {
        return getNum()
      }
       return randomNum
    }
    

    Might be a little faster, since it first tries to return a random number, and then checks if it's in the array.

    0 讨论(0)
  • 2021-01-20 08:10

    Build the complementary array and pick random values from it.

    var list2 = new Array();
    for(var i=0; i<30; i++)
      if(!list.contains(i))
        list2.push(i);
    

    Then:

    var rand = list2[Math.floor(Math.random() * list2.length)];
    
    0 讨论(0)
  • 2021-01-20 08:11

    Assuming your list is reasonable small in size, create a list of numbers that are not in the array and then select a number from that array at random.

    0 讨论(0)
  • 2021-01-20 08:14

    You need a while loop that tests if rand is in your restricted array and, if so, re-generate a new random number:

    var rand;
    do {
        rand = Math.floor(Math.random() * 31); // re-randomize, 0 to 30 inclusive
    } while ($.inArray(rand, restricted) > -1);
    return rand;
    

    http://jsfiddle.net/mblase75/dAN8R/

    Don't want jQuery? You can replace $.inArray(rand, restricted) with restricted.indexOf(rand) if you use this polyfill for old browsers.

    0 讨论(0)
  • 2021-01-20 08:15
    function RandomValueNotInArray(array)
    {
        var e;
        do
        {
            e = Math.random() * 31; // n + 1
        } while (array.contains(e))
        return e;
    }
    
    0 讨论(0)
提交回复
热议问题