Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check at least two out of ten booleans are true

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.

like image 789
Shabib Avatar asked Jan 19 '26 02:01

Shabib


1 Answers

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;
like image 88
Paul R Avatar answered Jan 21 '26 22:01

Paul R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!