随机选择并为每个选择重复特定次数

时间:2017-10-06 12:46:53

标签: javascript arrays random repeat

我希望从数组中随机选择一个项目,直到指定了最多重复时间。

var array = ["cat", "dog"];
var maxRepeat = 10;

我想每次10次返回猫狗,按随机顺序共计20次。 类似的东西:

cat
cat
dog
cat
dog
dog
cat
cat
dog
cat
dog
dog
dog
cat
cat
dog
cat
cat
dog
dog

4 个答案:

答案 0 :(得分:2)

var array = ["cat", "dog"];
var maxRepeat = 10;
var occObj= {};


for(var i = 0; i < array.length * maxRepeat; i++){
    var  occ = array[Math.floor(Math.random() * array.length)];

    if(occObj[occ]){
        if(occObj[occ].count < maxRepeat){
            occObj[occ].count++;
            console.log(occ);
        }else{
            i--; //if the particular value was displayed "maxRepeat" times already, we need to make sure we run the loop again
        }   
    }else{
        occObj[occ] = {}
        occObj[occ].count = 1;
        console.log(occ);
    }
}

我使用object来存储特定值的显示次数。

答案 1 :(得分:2)

你可以使用简单的for循环,然后使用push或unshift,其中每个元素都有50%的几率。

&#13;
&#13;
var array = ["cat", "dog"];
var maxRepeat = 10;

const random = function(arr, n) {
  var c = 0,r = [],total = n * arr.length;
  for (var i = 0; i < total; i++) {
    var rand = Math.random() <= 0.5;
    var el = arr[c++ % arr.length]
    rand ? r.push(el) : r.unshift(el)
  }
  return r;
}

console.log(random(array, maxRepeat))
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以通过以下方式执行此操作

function shuffle(a) {
    for (let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
}

let arr = ["cat", "dog"];
let temp = [];
for(let str of arr){
    temp = temp.concat(Array(10).fill(str));
}

shuffle(temp);
console.log(temp);

答案 3 :(得分:1)

很难确切地知道你要求的是什么,但是这里的函数会返回一个随机"cat""dog"(每只动物10次;所有动物都筋疲力尽之后,它将返回null):

var array = ["cat", "dog"],
    maxRepeat = 10;

let getRandomAnimal = (() => {
        let totalAnimals = maxRepeat * array.length,
            animals = new Array(totalAnimals),
            index = 0;

        for (let i = 0; i < totalAnimals; ++i) {
            animals[i] = array[i % array.length];
        }

        animals.sort(() => Math.floor(Math.random() - 0.5));

        return () => {
            return ((index >= totalAnimals) ? null : animals[index++]);
        };
    })();