2017-02-20 37 views
1

我有一個數組,像這樣:分配到一個數組中的元素「輸出頻率」,用javascript

var arrA = [1lemon, 2lemons, 3lemons, 1orange, 2oranges, 3oranges, 1apple, 2apples, 3apples, 1banana, 2bananas, 3bananas, 1coconut, 2coconuts, 3coconuts]; 

...,我有這個功能洗牌:

 function shuffle(array) { 
      var currentIndex = array.length, temporaryValue, randomIndex; 

      // While there remain elements to shuffle... 
      while (0 !== currentIndex) { 

      // Pick a remaining element... 
      randomIndex = Math.floor(Math.random() * currentIndex); 
      currentIndex -= 1; 

      // And swap it with the current element. 
      temporaryValue = array[currentIndex]; 
      array[currentIndex] = array[randomIndex]; 
      array[randomIndex] = temporaryValue; 
      } 

      return array; 
     } 

arrA = shuffle(arrA); 

.. 。而當時我有一些代碼輸出隨機排列的水果,一次一個,並每4秒,就像這樣:

var text = arrA; 
var counter = 0; 
var elem = document.getElementById("changeText"); 
setInterval(change, 4000); 
function change() { 
elem.innerHTML = text[counter]; 
    counter++; 
    if(counter >= text.length) { counter = 0; } 
} 

他們將出現在一個div:

<div id="changeText"><p>pick fruit(s)</p></div> 

但是在這種方式下,數組中的所有元素都會出現在每個循環中(它們具有100%的出現可能性)。

如何使它們以某種頻率出現?

所以1fruit出現的50%的時候,當時的2fruits 30%,當時的3fruits 20%?

只是包裹我的腦海裏解決這個...

感謝您的想法,

回答

1

我建議使用概率的連續檢查和隨機數的其餘部分。

該函數首先將返回值設置爲最後一個可能的索引並迭代,直到隨機值的其餘部分小於實際概率。

概率必須總和爲1。

function getRandomIndexByProbability(probabilities) { 
 
    var r = Math.random(), 
 
     index = probabilities.length - 1; 
 

 
    probabilities.some(function (probability, i) { 
 
     if (r < probability) { 
 
      index = i; 
 
      return true; 
 
     } 
 
     r -= probability; 
 
    }); 
 
    return index; 
 
} 
 

 
function getPlural(number, word) { 
 
    return number === 1 ? word : word + 's'; 
 
} 
 

 

 
var i, 
 
    fruits = ['lemon', 'orange', 'apple', 'banana', 'coconut'], 
 
    probabilities = [0.5, 0.3, 0.2], 
 
    count = {}, 
 
    fruit, 
 
    value; 
 

 
fruits.forEach(function (a) { 
 
    var i; 
 
    for (i = 1; i <= 3; i++) { 
 
     count[i + getPlural(i, a)] = 0; 
 
    } 
 
}); 
 

 
for (i = 0; i < 1e6; i++) { 
 
    fruit = fruits[Math.floor(Math.random() * fruits.length)]; 
 
    value = getRandomIndexByProbability(probabilities) + 1; 
 
    count[value + getPlural(value, fruit)]++; 
 
} 
 

 
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

最好的,謝謝!將不得不深入代碼才能完全獲得它,但它看起來很棒。 – Peanuts

相關問題