tags:

views:

95

answers:

1

how to found all matches in a two dimensional array? java

+1  A: 

Basically you just iterate through the rows and columns, check if the content of the addressed cell is equal (!) in both matrices and store the result to another matrix, which is the result of your operation.

Don't forget to implement the mandatory checks for the matrices, otherwise the algorithm will definitly crash in case you provide 'illegal arguments'.

Variations: if you need java primitives (int or float), change the type of the arrays and do not use equals to compare but the == operator.

private boolean[][] findMatches(Object[][] array1, Object[][] array2) {
  if (notComparable(array1, array2) {
   return null;
  }

  boolean[][] result = new boolean[array1.length, array1[0].length];
  for (int row = 0; row < array1.length; row++) {
    for (int column = 0; column < array1.length; column++) {
      if (array1[row][column].equals(array2[row][column]) {
        result[row][column] = true;
      }
    }
  }
  return result;

}

private boolean notComparable(Object[][] array1, Object[][] array2) {

  // dummy implementation - add your checks here to guarantee
  // that the arrays are not null, not empty and of same size in each row

  return false;
}
Andreas_D