2017-10-06 133 views
-3

我想從數組中獲取一個隨機選擇的項目,直到指定了多少個最大重複時間。隨機選擇並重復每個選擇的具體時間

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 

回答

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

我使用對象來存儲特定值了多少次顯示。

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

2

您可以使用簡單的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))

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++]); 
     }; 
    })();