This question was inspired by an answer I was working on yesterday.
Let's say we have N inputs that evaluate to either true or false, what is the most efficient way to determine if X of those inputs are true?
Caveats:
- The inputs are not in an array, so if you convert them to an array please account for any overhead costs.
- By "most efficient" I mean in terms of best average case (although I would love to see best and worst case stats too).
Here are two of the methods I came across yesterday.
1) Think of the variables as Boolean inputs for a circuit and reduce them using a K-map
At first I thought this would be the most efficient means because it follows circuit logic, but I've definitely had second thoughts. As the number of inputs increases, the number of comparisons goes up exponentially
2 inputs:
1 of 2: if(1 OR 2)
2 of 2: if(1 AND 2)
3 inputs:
1 of 3: if(1 OR 2 OR 3)
2 of 3: if((1 AND 2) OR (1 AND 3) OR (2 AND 3))
3 of 3: if(1 AND 2 AND 3)
4 inputs:
1 of 4: if(1 OR 2 OR 3 OR 4)
2 of 4: if((1 AND 2) OR (1 AND 3) OR (1 AND 4) OR (2 AND 3) OR (2 AND 4) OR (3 AND 4))
3 of 4: if((1 AND 2 AND 3) OR (1 AND 2 AND 4) OR (1 AND 3 AND 4) OR (2 AND 3 AND 4))
4 of 4: if(1 AND 2 AND 3 AND 4)
... etc. ...
The best case scenario is fine (O(1)), but the worst case is far worse than...
2) A counter and sequential if statements
This performs in O(n) time always, which is OK, but I was hoping for a better best case.
counter = 0
if(input 1)
counter++
if(input 2)
counter++
if(input 3)
counter++
... etc. ...
if(counter >= X)
// true
What is a more efficient solution than either of these?