Javascript获取具有特定数组概率的随机结果 [英] Javascript Get Random result with probability for specific array
问题描述
我有一个数组,我需要按照下面的概率随机显示输出
i have a array and i need to do it randomly show the output by probability below are my code
var shirts = [
["images/fantastic-logo.png","12.65"],
["images/fantastic-word.png","10.00"],
["images/free-product.png","15.50"]
];
var pos = Math.floor((Math.random() * shirts.length) + 0);
$("#image").html($("<img/>").attr("src", shirts[pos][0]));
$(".price").html("$" + shirts[pos][1]);
我已经做了基本的math.random()使其随机显示图像,现在我需要使其具有概率显示,例如显示["images/fantastic-logo.png","12.65" ]为50%,["images/fantastic-word.png","10.00"]为25%,["images/free-product.png","15.50"]为25%.
i have do the basic math.random() to make it random show the image, now i need to make it show with probability, for example probability for showing ["images/fantastic-logo.png","12.65"] was 50%, ["images/fantastic-word.png","10.00"] was 25%, ["images/free-product.png","15.50"] was 25%.
感谢大家的帮助
推荐答案
一个选项是添加第三个元素,该元素指示概率的权重.
One option is add a third element which indicate the weight of probability.
在下面的示例中,fantastic-logo.png
有2个代表50%,其他2个只有1个代表25%.
In the example below fantastic-logo.png
has 2 to represent 50% and the other 2 only as 1 to represent 25% each.
然后创建一个4元素数组[0,0,1,2]
-这表示元素0具有50%的机会.元素1的几率是25%,元素2的几率也是25%.
Then create a 4 element array [0,0,1,2]
- This represent element 0 has 50% chance. element 1 has 25% chance and element 2 has 25% as well.
从新创建的数组中进行随机选择,并将该值用作位置.
Make random from the newly created array and use the value as the position.
赞:
var shirts = [
["images/fantastic-logo.png", "12.65", 2],
["images/fantastic-word.png", "10.00", 1],
["images/free-product.png", "15.50", 1]
];
//Create a 4 element array based on probability weight
var probability = shirts.map((v, i) => Array(v[2]).fill(i)).reduce((c, v) => c.concat(v), []);
//Random select from probability array
var pos = probability[Math.floor((Math.random() * probability.length))];
$("#image").html($("<img/>").attr("src", shirts[pos][0]));
$(".price").html("$" + shirts[pos][1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="image"></div>
<div class="price"></div>
这篇关于Javascript获取具有特定数组概率的随机结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!