1. Overview

boolean is one of Java’s primitives. It’s a pretty straightforward data type with only two values: true and false.

In this tutorial, we’ll look into a problem: checking if there are at least two true in the given three booleans.

2. Introduction to the Problem

The problem is pretty straightforward. We’ll be given three booleans. If at least two of them are true, our method should return true.

Solving the problem isn’t a challenge for us. However, in this tutorial, we’ll explore a few nice solutions. Further, we’ll discuss if each approach can be easily extended to solve a general problem: given n booleans, check if at least x from them are true.

We’ll verify each approach by unit tests. Therefore, let’s first create a Map object to hold test cases and the expected results:

static final Map<boolean[], Boolean> TEST_CASES_AND_EXPECTED = ImmutableMap.of(
    new boolean[]{true, true, true}, true,
    new boolean[]{true, true, false}, true,
    new boolean[]{true, false, false}, false,
    new boolean[]{false, false, false}, false
);

As the code above shows, the TEST_CASES_AND_EXPECTED map carries four scenarios and their expected results. Later, we’ll go through this map object and pass each boolean array as the parameter to each approach and verify if the method returns the expected value.

Next, let’s see how to solve the problem.

3. Looping Through the Three Booleans

The most straightforward idea to solve the problem could be walking through the three given booleans and counting trues.

We stop the checking and return true once the counter is greater than or equal to 2. Otherwise, the number of trues in the three booleans is less than 2. Thus, we return false:

public static boolean twoOrMoreAreTrueByLoop(boolean a, boolean b, boolean c) {
    int count = 0;
    for (boolean i : new Boolean[] { a, b, c }) {
        count += i ? 1 : 0;
        if (count >= 2) {
            return true;
        }
    }
    return false;
}

Next, let’s use our TEST_CASES_AND_EXPECTED map to test if this method works:

TEST_CASES_AND_EXPECTED.forEach((array, expected) -> 
  assertThat(ThreeBooleans.twoOrMoreAreTrueByLoop(array[0], array[1], array[2])).isEqualTo(expected));

If we run this test, unsurprisingly, it passes.

This approach is pretty easy to understand. Further, suppose we change the method’s argument to a boolean array (or a Collection) and an int x. In that case, it can be easily extended to become a generic solution to solving the problem: given n booleans, check if at least x of them are true:

public static boolean xOrMoreAreTrueByLoop(boolean[] booleans, int x) {
    int count = 0;
    for (boolean i : booleans) { 
        count += i ? 1 : 0;
        if (count >= x) {
            return true;
        }
    }
    return false;
}

4. Converting Booleans Into Numbers

Similarly, we can convert the three booleans into numbers and calculate their sum and check if it’s 2 or greater:

public static boolean twoOrMoreAreTrueBySum(boolean a, boolean b, boolean c) {
    return (a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0) >= 2;
}

Let’s execute the test to make sure it works as expected:

TEST_CASES_AND_EXPECTED.forEach((array, expected) -> 
  assertThat(ThreeBooleans.twoOrMoreAreTrueBySum(array[0], array[1], array[2])).isEqualTo(expected));

We can also turn this approach into a general solution to check at least x trues from n booleans:

public static boolean xOrMoreAreTrueBySum(Boolean[] booleans, int x) {
    return Arrays.stream(booleans)
      .mapToInt(b -> Boolean.TRUE.equals(b) ? 1 : 0)
      .sum() >= x;
}

We’ve used the Stream API to convert each boolean into an int and calculate the sum in the code above.

5. Using Logical Operators

We’ve solved the problem by converting booleans into integers. Alternatively, we can use logical operations to determine if at least two of three booleans are true.

We can perform the logical AND (&&) operation on every two booleans. So, we’ll do three AND operations on the given three booleans. If two of three booleans are true, then at least one logical AND operation should result in true:

public static boolean twoOrMoreAreTrueByOpeators(boolean a, boolean b, boolean c) {
    return (a && b) || (a && c) || (b && c);
}

Next, if we test this method using the TEST_CASES_AND_EXPECTED map, it passes, too:

TEST_CASES_AND_EXPECTED.forEach((array, expected) -> 
  assertThat(ThreeBooleans.twoOrMoreAreTrueByOpeators(array[0], array[1], array[2])).isEqualTo(expected));

Now, let’s think about if we can extend this approach to the general case. It works only when x is 2. Also, if the n is large enough, we may need to build a long logical operation chain.

Therefore, it’s not suitable for a general problem.

6. Using the Karnaugh Map

Karnaugh Map is a method of simplifying boolean algebra expressions. Also, we can write the expression from a Karnaugh Map. Therefore, sometimes, it can help us solve complex boolean algebra problems.

Next, let’s see how to solve this problem using the Karnaugh Map. Given that we have three booleans, A, B, and C, we can build a Karnaugh Map:

      | C | !C
------|---|----
 A  B | 1 | 1 
 A !B | 1 | 0
!A !B | 0 | 0
!A  B | 1 | 0

In the table above, A, B, and C indicate their true values. Oppositely, !A, !B, and !C mean their false values.

So, as we’ve seen, the table covers all possible combinations of the given three booleans. Moreover, we can find all combination cases in which at least two booleans are true. For these cases, we’ve written ‘1’ to the table. Therefore, there are two groups containing the ones: the first row (group 1) and the first column (group 2).

Thus, the final boolean algebra expression to produce one would be: (the expression to obtain all ones in group1 ) || (the expression to obtain all ones in group2)

Next, let’s divide and conquer.

  • Group 1 (the first row) – A and B are both true. No matter what value C has, we’ll have one. Therefore, we have: A && B
  • Group 2 (the first column) – First, C is always true. Moreover, there must be at least one true in A and B. Therefore, we get: C && (A || B)

Finally, let’s combine the two groups and get the solution:

public static boolean twoorMoreAreTrueByKarnaughMap(boolean a, boolean b, boolean c) {
    return (c && (a || b)) || (a && b);
}

Now, let’s test if the method works as expected:

TEST_CASES_AND_EXPECTED.forEach((array, expected) -> 
  assertThat(ThreeBooleans.twoorMoreAreTrueByKarnaughMap(array[0], array[1], array[2])).isEqualTo(expected));

If we execute the test, it passes. That is to say, the method does the job.

However, if we try to use this method to solve the general problem, it could be a difficult job to produce the table when n is large.

Therefore, even though the Karnaugh Map is good at solving complex boolean algebra problems, it’s not suitable for some dynamic and general tasks.

7. Using the xor Operator

Finally, let’s have a look at another interesting approach.

In this problem, we’re given three booleans. Further, we’ve known a boolean can only have two different values: true and false.

So, let’s first take any two booleans from the three, say a and b. Then, we check the result of the expression a != b:

  • a != b is true – either a or b is true. So, if c is true, then we have two trues. Otherwise, we have two false in the three booleans. That is to say, c‘s value is the answer.
  • a != b is falsea and b have the same value. Since we have only three booleans, a (or b) value is the answer.

Therefore, we can conclude the solution: a != b ? c : a. Moreover, the a != b check is actually an XOR operation. Hence, the solution can be as simple as:

public static boolean twoOrMoreAreTrueByXor(boolean a, boolean b, boolean c) {
    return a ^ b ? c : a;
}

When we test the method using the TEST_CASES_AND_EXPECTED map, the test will pass:

TEST_CASES_AND_EXPECTED.forEach((array, expected) -> 
  assertThat(ThreeBooleans.twoOrMoreAreTrueByXor(array[0], array[1], array[2])).isEqualTo(expected));

This solution is pretty compact and tricky. However, we cannot extend it to solve the general problem.

8. Conclusion

In this article, we’ve explored a few different approaches to check if there are at least two trues in three given booleans.

Moreover, we’ve discussed which approach can be easily extended to solve a more general problem: check if there are at least x trues in n booleans.

As always, the complete source code is available over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.