An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.
My solution follow
As an addition to @TofuBeer TofuBeer's excellent post, consider @pdox pdox's answer:
static boolean five(final boolean a, final boolean b, final boolean c)
{
return a == b ? a : c;
}
Consider also its disassembled version as given by "javap -c":
static boolean five(boolean, boolean, boolean);
Code:
0: iload_0
1: iload_1
2: if_icmpne 9
5: iload_0
6: goto 10
9: iload_2
10: ireturn
pdox's answer compiles to less byte code than any of the previous answers. How does its execution time compare to the others?
one 5242 ms
two 6318 ms
three (moonshadow) 3806 ms
four 7192 ms
five (pdox) 3650 ms
At least on my computer, pdox's answer is just slightly faster than @moonshadow moonshadow's answer, making pdox's the fastest overall (on my HP/Intel laptop).