Hey guys I was wondering if there was any way to return a certain fraction of a bunch of booleans in java. Simply put I would like to find out if there is a way to create a method that when given four booleans if three of them are true it returns true but if less than three are true it returns false. I know this might be hard to understand and if you don't understand just post a comment saying so.
0
votes
8 Answers
3
votes
2
votes
Weird question ... anyway, here's a possible solution for just 4 booleans:
public boolean booleanFraction(boolean a, boolean b, boolean c, boolean d) {
int ia = a ? 1 : 0;
int ib = b ? 1 : 0;
int ic = c ? 1 : 0;
int id = d ? 1 : 0;
return ia + ib + ic + id == 3;
}
For a more general solution, here's a method that receives as parameters the number of booleans that need to be true
for considering true
the whole expression, and a greater than zero variable number of boolean values:
public static boolean booleanFraction(int number, boolean... bools) {
int acc = 0;
for (boolean b : bools)
acc += b ? 1 : 0;
return acc == number;
}
Call it like this, for the example in the question:
booleanFraction(3, true, true, true, false);
> true
booleanFraction(3, false, false, true, false);
> false
2
votes
1
votes
0
votes
If you want your answer as a boolean
expression, you can try,
boolean atLeastThree(boolean a, boolean b, boolean c, boolean d) {
return a ? (b && (c || d) || (c && d)) : (b && c && d);
}
Counting the number of true
s is a little more elegant and easy to understand,
boolean atLeastThree(boolean a, boolean b, boolean c, boolean d) {
return (a ? 1 : 0) +
(b ? 1 : 0) +
(c ? 1 : 0) +
(d ? 1 : 0) > 2;
}
0
votes
0
votes
A variation of my answer for the 2-out-of-3 problem:
boolean atLeastThree(boolean a, boolean b, boolean c, boolean d)
{
int n = -3;
if (a) n++;
if (b) n++;
if (c) n++;
if (d) n++;
return (n >= 0);
}