【发布时间】:2018-04-09 15:53:44
【问题描述】:
我正在尝试为报价机制作一个加权随机数生成器,如果选择了某个项目,则会从另一组中选择一个,而无需进入并更改所有数字。
基本上,有一个主要的引号数组,其中混入了数字。这些数字对应于列表,并且它们需要更有可能被选中,具体取决于列表中有多少项目。 (例如,如果 1 被选中,并且对应于其中包含十个项目的数组,那么它被选中的可能性应该是字符串的十倍,因为它对应于十个字符串。)
因此,我决定将索引从简单的无偏随机数生成器转换为本质上由随机数生成器运行的抽奖机,其中主数组中的每个项目都放置一个“票”(或它们的索引他们拥有的每个字符串的数字。例如,如果我们使用前面的一个和其他两个字符串,它应该像这样工作:
input=["I am a string!",1,"Me Too!"];
output=[0,1,1,1,1,1,1,1,1,1,1,2];
然后从输出数组中随机选择一个数字,然后对应于主数组中的一个项目。如果选择1,则从1对应的数组中选择一个字符串。
但我打算在里面放很多东西。我已经有 40 多个,并计划添加更多,所以我做了一些东西来为我制作输出数组。 唯一的问题是,它不能正常工作。它应该输出 [0,1,2,3,3,3,4,6,6,6,6,7],而不是输出 [3,3,3,7,7,7,7]。
//main array
var main=["one","two","three",1,"fourth",2,"fifth",3]
//array corresponding to 1
var first=["a","b","c"];
//array corresponding to 2. 2 will not be par of this array
var second=["1","2","3"];
//array corresponding to 3
var third=["red","yellow","green","blue"];
//weights
var weights=[];
//weight pusher
for (var i = 0; i < main.length; i++) {
//weight adder
if (!Number.isNaN(main[i])) {
switch (main[i]) { //If it gets to this point, main[i] should be 1, 2, or 3.
case 1:
//add i to the array once for every item in first (three times)
for (var j = 0; j < first.length; j++) {
weights.push(i)
}
break;
case 2:
//do nothing
break;
case 3:
//add i to the array once for every item in third (four times)
for (var j = 0; j < third.length; j++) {
weights.push(i)
}
break;
}
}else {
//If it's a regular string, add one i to the array.
weights.push(i);
};
};
console.log(weights); //Should output [0,1,2,3,3,3,4,6,6,6,6,7],instead outputs [3,3,3,7,7,7,7]
【问题讨论】:
-
有更好的方法来实现加权随机数生成器。
标签: javascript arrays for-loop random