Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check ALL elements of a boolean array are true

I have a boolean array whose size depends on the size of a randomly selected string.

So I have something like this:

boolean[] foundLetterArray = new boolean[selectedWord.length()];

As the program progresses, this particular boolean array gets filled with true values for each element in the array. I just want to print a statement as soon as all the elements of the array are true. So I have tried:

if(foundLetterArray[selectedWord.length()]==true){
    System.out.println("You have reached the end");
}

This gives me an out of bounds exception error. I have also tried contains() method but that ends the loop even if 1 element in the array is true. Do I need a for loop that iterates through all the elements of the array? How can I set a test condition in that?

like image 700
Daybreak Avatar asked Sep 05 '13 08:09

Daybreak


People also ask

How do you check if all values in array are true?

The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.

How do I make a boolean array true?

boolean[] isPrime = new boolean[10]; Arrays. fill(isPrime, true); This will assign all the elements of the array with true. Because by default the boolean array has all elements as false.

How do you check if all elements of an array are true Python?

Python all() Function The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.


2 Answers

Using the enhanced for loop, you can easily iterate over an array, no need for indexes and size calculations:

private static boolean allTrue (boolean[] values) {
    for (boolean value : values) {
        if (!value)
            return false;
    }
    return true;
}
like image 131
Peter Walser Avatar answered Sep 22 '22 22:09

Peter Walser


There is a Java 8 one-liner for this:

boolean allTrue(boolean[] arr) {
    return IntStream.range(0, arr.length).allMatch(i -> arr[i]);
}
like image 26
Paul Boddington Avatar answered Sep 22 '22 22:09

Paul Boddington