简体   繁体   English

选择数组中没有的随机值

[英]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: 您需要一个while循环来测试rand是否在您的restricted数组中,如果是,则重新生成一个新的随机数:

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/ http://jsfiddle.net/mblase75/dAN8R/

Don't want jQuery? 不需要jQuery吗? You can replace $.inArray(rand, restricted) with restricted.indexOf(rand) if you use this polyfill for old browsers . 您可以替换$.inArray(rand, restricted)restricted.indexOf(rand)如果你使用这个填充工具对旧的浏览器

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

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. 这样,我可以继续删除项目,而只是从位置0到数组长度-1中随机选择项目,而不必两次选择相同的内容。

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. 另一种方法是将0到30之间的数字随机化,并在数组中找到它时继续进行。 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 . 您可以使用filter

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

});

PHP in 2 lines: PHP分2行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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