# 2D Boolean Array

• 02-02-2014, 03:58 AM
JesusChrist
2D Boolean Array
Hello all,

I'm creating a 4x4 2D array. I need to be notified, or gain a value when all elements have been turned true. Is this as simple as "If the2DArray[] = true { blah blah }" ?

Thanks!
• 02-02-2014, 11:16 AM
JosAH
Re: 2D Boolean Array
No, Java doesn't work that way, you either test if all values in your matrix are 'true' or you count the number of elements that are set from 'false' to 'true' (or vice versa) each time you set one of the matrix elements.

kind regards,

Jos
• 02-03-2014, 03:50 AM
zFollette
Re: 2D Boolean Array
It is really simple actually.

Code:

```public static boolean allTrue(boolean[][] bools) {         for (int x = 0; x < bools.length; x++) { //Iterate through all x's             for (int y = 0; y < bools[0].length; y++) { //Iterate through all y's                 if (!bools[x][y]) { //Check if the boolean at x,y is false                     return false; //If it is, all of the boolean must not be true, return false;                 }             }         }         return true; //If the boolean is still running, all booleans in bools must be true, return true.     }```
• 02-03-2014, 03:57 AM
AlexGraal
Re: 2D Boolean Array
It's simple but not simple enough...

Would be great if you could do something like
Code:

```boolean[][] values = {{true,true,true},{true,true,true},{true,true,true}}; if(values[][] == true) System.out.println("All true!");```
• 02-03-2014, 04:04 AM
zFollette
Re: 2D Boolean Array
Quote:

Originally Posted by AlexGraal
It's simple but not simple enough...

Would be great if you could do something like
Code:

```boolean[][] values = {{true,true,true},{true,true,true},{true,true,true}}; if(values[][] == true) System.out.println("All true!");```

Well, with that code I just provided, it is that easy, easier even:

Code:

```if (allTrue(values)) { }```
• 02-03-2014, 03:50 PM
jim829
Re: 2D Boolean Array
As an alternative of arrays of booleans you may want to check out the BitSet class.

Regards,
Jim
• 02-03-2014, 05:25 PM
JosAH
Re: 2D Boolean Array
Quote:

Originally Posted by jim829
As an alternative of arrays of booleans you may want to check out the BitSet class.

Hm, the shortest solution with a BitSet I can come up with is bitset.cardinality() == 16 (for a 4x4 boolean matrix), but under the hood the BitSet uses the Long.bitCount( ... ) method to count its number of set bits; quite hackish, compared to a simple checking loop ...

kind regards,

Jos
• 02-03-2014, 06:23 PM
jim829
Re: 2D Boolean Array
Yeah, I wasn't certain and I didn't look at the code. I just checked the API and it said something like "maintains a vector of boolean values."

Regards,
Jim
• 02-03-2014, 07:14 PM
zFollette
Re: 2D Boolean Array
Is a workaround really necessary in this situation?