If x amount of these facts are true, then return y

≯℡__Kan透↙ 提交于 2019-12-11 07:36:57

问题


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)

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.

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.

Thanks in advance for your help!


Bonus Round! (I misinterpreted my aim)

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?


回答1:


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

You can do this by using a lua style ternary:

matches = (condition == check) and 1 or 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.

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)


来源:https://stackoverflow.com/questions/56873993/if-x-amount-of-these-facts-are-true-then-return-y

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!