我想从数组中获取一个随机选择的项目,直到指定了多少个最大重复时间。随机选择并重复每个选择的具体时间
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
我想从数组中获取一个随机选择的项目,直到指定了多少个最大重复时间。随机选择并重复每个选择的具体时间
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
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);
}
}
我使用对象来存储特定值了多少次显示。
你可以做到这一点通过以下方式
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);
您可以使用简单的for
循环,然后使用push或unshift,其中每个元素都有50%的机会。
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))
很难知道你要问什么了,但这里是一个将返回一个随机"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++]);
};
})();