我正在用lua语言用Corona编写一个游戏。我很难想出这样一个系统的逻辑;
我有不同的东西。我想要一些项目有1/1000的机会被选中(一个独特的项目),我希望一些有1/10,一些2/10等等。
我在考虑填一张桌子,随便挑一件。例如,我会将100的"X“项添加到表中,而不是1 "Y”项。所以,通过从0,101中随机选择,我实现了我想要的,但我想知道是否还有其他的方法来实现它。
发布于 2014-05-02 22:48:13
items = {
Cat = { probability = 100/1000 }, -- i.e. 1/10
Dog = { probability = 200/1000 }, -- i.e. 2/10
Ant = { probability = 699/1000 },
Unicorn = { probability = 1/1000 },
}
function getRandomItem()
local p = math.random()
local cumulativeProbability = 0
for name, item in pairs(items) do
cumulativeProbability = cumulativeProbability + item.probability
if p <= cumulativeProbability then
return name, item
end
end
end因此,如果增加项目的概率(或添加项),则需要从其他项中减去。这就是为什么我把1/10写成100/1000的原因:当你有一个共同的分母时,更容易看到事物是如何分布的,并更新它们。
您可以确认您得到了预期的分发,如下所示:
local count = { }
local iterations = 1000000
for i=1,iterations do
local name = getRandomItem()
count[name] = (count[name] or 0) + 1
end
for name, count in pairs(count) do
print(name, count/iterations)
end发布于 2016-12-15 14:18:22
我相信这个答案要容易得多--尽管执行速度稍慢一些。
local chancesTbl = {
-- You can fill these with any non-negative integer you want
-- No need to make sure they sum up to anything specific
["a"] = 2,
["b"] = 1,
["c"] = 3
}
local function GetWeightedRandomKey()
local sum = 0
for _, chance in pairs(chancesTbl) do
sum = sum + chance
end
local rand = math.random(sum)
local winningKey
for key, chance in pairs(chancesTbl) do
winningKey = key
rand = rand - chance
if rand <= 0 then break end
end
return winningKey
endhttps://stackoverflow.com/questions/23437573
复制相似问题