温馨提示:本文翻译自stackoverflow.com,查看原文请点击:string - If x amount of these facts are true, then return y
lua string find

string - 如果这些事实的x数量为真,则返回y

发布于 2020-03-27 12:08:26

"Match"如果所有事实都是真实的,我有一个返回的函数(尽管我现在似乎是通过摆弄我当前的困境来打破它的,但这不是我的主要问题)。

function dobMatch(x)
local result = "YearOfBirth" .. x .. "MonthOfBirth"
    if (result:find("DayOfBirth")~= nil and result:find("MonthOfBirth")~= nil and result:find("YearOfBirth")~= nil) then
        return "Match"
    else
        return nil
    end
end

dobList = {dobMatch("DayOfBirth"), dobMatch("Day")}

print(#dobList)

我的实际问题是,如果我要说的是事实中的任何两个,result:find("DayOfBirth")~= nil and result:find("MonthOfBirth")~= nil and result:find("YearOfBirth")而不是全部三个。

请记住,我的实际问题有12个事实,其中10个必须为真,因此要遍历所有组合将非常漫长。

在此先感谢您的帮助!


奖金回合!(我误解了我的目标)

如果我想对这些事实进行加权,即DayOfBirth比Month重要得多,我是否只需将1(在Nifim答案中)更改为我希望对其加权的值即可?

查看更多

查看更多

提问者
Bee
被浏览
177
Nifim 2019-07-04 00:15

您可以更改问题的性质以使其成为数学问题。

您可以通过使用lua样式三元来实现

matches = (condition == check) and 1 or 0

这里发生的情况是,当条件为true时,如果表达式为false,则返回1;为0。这意味着您可以将该结果添加到变量中以跟踪匹配项。这使您可以简单地评估匹配数。

如本例所示,我建议将检查语句移出if语句条件,以使代码更加整洁:

function dobMatch(x)
    local result = "YearOfBirth" .. x .. "MonthOfBirth"

    local matches = (result:find("DayOfBirth")~= nil) and 1 or 0
    matches = matches + ((result:find("MonthOfBirth")~= nil) and 1 or 0)
    matches = matches + ((result:find("YearOfBirth")~= nil) and 1 or 0)

    if ( matches >= 2) then
        return "Match"
    else
        return nil
    end
end

dobList = {dobMatch("DayOfBirth"), dobMatch("Day")}

print(#dobList)