Wednesday, 21 November 2018

language agnostic - 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.


Answer



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;

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...