使用DIV的随机排列在JavaScript中的概率
问题描述:
我尝试做一个JavaScript脚本,我尝试做一个建筑,随机墙壁,门,窗和装饰(和随机层)使用DIV的随机排列在JavaScript中的概率
但是我试着加上一个概率: 更多概率门和概率窗不在楼下 更多概率窗和概率门不在楼上 我得到了楼上和楼下的情况。
你能帮我吗?
答
看看我在我的代码片段中写的pickItem
函数。在这种情况下,我已经设置好了,所以你传入了两个参数,一个是items
(即你的items
数组),另一个是你可以创建的chance
数组。 chance
数组定义了您的items
阵列中的每个元素被选中的机会。看看代码片段,看看我是如何根据我的letters
阵列创建一个chance
阵列的。
如果您观察输出结果,你可以看到,该项目“一”从letters
通常采摘1/2或1/2以上的时间,因为它已经被赋予了50%
因此,如果将此逻辑应用于您的items
阵列,您将能够使其从items
中挑选出比其他元素更频繁的特定元素。
function rand(intMin, intMax) {
return Math.floor(Math.random() * (intMax - intMin + 1) + intMin);
}
let letters = ['a', 'b', 'c', 'd', 'e', 'f']; // dummy data, this is your items array
/*
a --> 50%
b --> 20%
c --> 10%
d --> 5%
e --> 10%
f --> 5%
*/
// The following chances can be defined in an array like so:
// a b c d e f
let chance = [50, 20, 10, 5, 10, 5]; // chance as a percentage (%)
function pickItem(items, chance) { // Pick an item from the letters array as defined by the chance
let randIndex = rand(0, items.length - 1); // pick a random letter index
while (!(chance[randIndex] >= rand(1, 100))) { // If the chance of that letter being picked isnt met, then pick a new letter
randIndex = rand(0, items.length - 1); // pick a new random letter index
}
return items[randIndex]; // return the letter when found
}
// To show the function working we can print a bunch of letters:
for (var i = 0; i < letters.length * 2; i++) { // Print out a picked item 12 times
console.log(pickItem(letters, chance)); // At least 6 of these items (1/2 the time) should be 'a'
}