如果这些事实的x数量为真,则返回y [英] If x amount of these facts are true, then return y

查看:101
本文介绍了如果这些事实的x数量为真,则返回y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I had a function which was returning "Match" if all the facts are true (although I now seem to have broken it by fiddling around with my current predicament, but that's not my main question).

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")而不是全部三个.

My actual question, is that if I trying to say that any 2 of the facts result:find("DayOfBirth")~= nil and result:find("MonthOfBirth")~= nil and result:find("YearOfBirth") rather than all 3.

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

Please bare in mind that my actual issue has 12 facts, of which 10 need to be true so it would be very long to iterate through all the combinations.

提前感谢您的帮助!

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

Bonus Round! (I misinterpreted my aim)

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

If I wanted to weight these facts differently, i.e. DayOfBirth is far more important than Month would I just change the 1 (in Nifim answer) to the value I want it weighted?

推荐答案

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

You can change the nature of your problem to make it a math problem.

您可以使用 lua风格三元:

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

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

What happens here is when the condition is true the expression returns a 1 if it is false a 0. this means you can add that result to a variable to track the matches. This lets you evaluate the number of matches simply.

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

As shown In this example I suggest moving the checks out side of the if statement condition to keep the code a little neater:

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)

这篇关于如果这些事实的x数量为真,则返回y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆