简体   繁体   中英

select random value NOT in array

如何选择不在此数组中的随机值(0到30)?

var list = new Array(1,3,4,7,8,9);

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)];

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 .

假设列表的大小合理,请创建一个不在数组中的数字列表,然后从该数组中随机选择一个数字。

function RandomValueNotInArray(array)
{
    var e;
    do
    {
        e = Math.random() * 31; // n + 1
    } while (array.contains(e))
    return e;
}

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.

I would probably make an array or linked list from which I would subtract the unwanted items. That way I could keep removing items and just randomly select items from position 0 to the array's length - 1 without having to select the same thing twice.

Another way of doing it is to randomize a number between 0 and 30 and to keep doing it while it is found in the array. The only problems with that is knowing when the array is full (to get rid of infinite loops) and that it is a whole lot more processor intensive.

you can use filter .

var filteredArray = list.filter(function(e){
  return e!= Math.floor(Math.random() * (31));

});

PHP in 2 lines:

$result = array_diff(range(1,30), array(1,3,4,7,8,9)); 
echo $result[array_rand($result)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM