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!

Printable View

- 02-02-2014, 03:58 AMJesusChrist2D 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 AMJosAHRe: 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 AMzFolletteRe: 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 AMAlexGraalRe: 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 AMzFolletteRe: 2D Boolean Array
- 02-03-2014, 03:50 PMjim829Re: 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 PMJosAHRe: 2D Boolean Array
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 PMjim829Re: 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 PMzFolletteRe: 2D Boolean Array
Is a workaround really necessary in this situation?