3
votes

In a case where at least two out of three booleans are true, this is the easiest way to find out:

BOOL a, b, c;
-(BOOL)checkAtLeastTwo
{
  return a && (b || c) || (b && c); 
}

What will be the optimal solution if there is ten booleans and at least two of them needs to be true? Thanks in advance.

2

2 Answers

5
votes

Your original implementation is sub-optimal - you can just sum true values:

return (int)a + (int)b + (int)c >= 2;

Obviously you can extend this to 10 variables:

return (int)a + (int)b + (int)c + (int)d + (int)e +
       (int)f + (int)g + (int)h + (int)i + (int)j >= 2;
1
votes

In C you can just check sum of your variables

return a + b + .... + n >= 2;

If implicit conversion from boolean to integer doesn't in your language, you can simply convert your variables to integer and check sum of converted values.