java - Measuring overlap between arrays -
given several arrays in java (i'll looping through keys stored in hashmap), want able identify (based on boolean[]
keys stored) indices true
in of them, , false
.
example:
{true, true,false} {true,false,false} {true,false, false}
would yield index 0 having true values, , index 2 having false values.
one idea have convert boolean array array of ints, summing values, , if summed array index = numarrays, true in of them. similarly, if summed array index 0, false in of them.
am not sure how go doing in efficient way (in java), letalone if method achieve desired result.
is there way convert array of booleans ints? if not, easiest alternative instantiate new array of ints, , loop through boolean array populate new array?
assuming arrays have same number of elements can try this:
public static void main(string[] args) { boolean[] array1 = new boolean[] {true,true,false}; boolean[] array2 = new boolean[] {true,false,false}; boolean[] array3 = new boolean[] {true,false,false}; boolean[] array4 = new boolean[] {true,false,false}; compareandprintcommonindicesforarrays(array1, array2, array3); } public static boolean compareandprintcommonindicesforarrays(boolean[] ...arrays) { boolean result =true; boolean itemtocompare; int elementstocompare = arrays[0].length; for(int itemindex=0; itemindex<elementstocompare; itemindex++) { result = true; itemtocompare = arrays[0][itemindex]; for(int arrayindex = 0; arrayindex<arrays.length;arrayindex++) { if(itemtocompare != arrays[arrayindex][itemindex]) { result = false; } } if(result) system.out.println(itemindex); } return result; }
it prints:
0 2
the code traverse indices , every index compare elements array @ index. if same index printed.
Comments
Post a Comment