1

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gamora
  • 337
  • 2
  • 18
  • 1
    You can turn it into a math problem rather then a boolean problem. `(result:find("MonthOfBirth")~= nil and 1 or 0) + (result:find("YearOfBirth") and 1 or 0) ...so on` then check your final result is `> 10` – Nifim Jul 03 '19 at 15:59

1 Answers1

2

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)
Nifim
  • 4,758
  • 2
  • 12
  • 31
  • Sorry just noticed an issue (but not really with your logic) my dob list is returning the number of original elements rather than matched. I.e. dobMatch("Day") (although nil) is being counted. I also misinterpreted something when I asked my question added in an edit to the original question! – Gamora Jul 04 '19 at 15:52