首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据项目的稀缺性设置从列表中选择随机项目的正确逻辑,即“罕见”“正常”

如何根据项目的稀缺性设置从列表中选择随机项目的正确逻辑,即“罕见”“正常”
EN

Stack Overflow用户
提问于 2014-05-02 21:57:08
回答 2查看 1.2K关注 0票数 4

我正在用lua语言用Corona编写一个游戏。我很难想出这样一个系统的逻辑;

我有不同的东西。我想要一些项目有1/1000的机会被选中(一个独特的项目),我希望一些有1/10,一些2/10等等。

我在考虑填一张桌子,随便挑一件。例如,我会将100的"X“项添加到表中,而不是1 "Y”项。所以,通过从0,101中随机选择,我实现了我想要的,但我想知道是否还有其他的方法来实现它。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-05-02 22:48:13

代码语言:javascript
复制
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的原因:当你有一个共同的分母时,更容易看到事物是如何分布的,并更新它们。

您可以确认您得到了预期的分发,如下所示:

代码语言:javascript
复制
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
票数 6
EN

Stack Overflow用户

发布于 2016-12-15 14:18:22

我相信这个答案要容易得多--尽管执行速度稍慢一些。

代码语言:javascript
复制
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
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23437573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档