/*
  Matrix multiplication.  For example,

  1,2,3             1, 2,-2                   14 16 19 
  4,5,6    times   -1,-2,-3    is equal to    29 34 31
                    5, 6, 9
 */
public final class MatrixMultiplication {

   public static void main (final String[] args) {

      // Sample input
      final int[][] matrix1 = {{1,2,3},{4,5,6}};             // sample 2x3 matrix
      final int[][] matrix2 = {{1,2},{3,4},{5,6},{7,9}};     // sample 4x2 matrix
      final int[][] matrix3 = {{1,2,-2},{-1,-2,-3},{5,6,9}}; // sample 3x3 matrix

      // Multiply
      final int[][] matrix = matrixMultiply (matrix1, matrix3);

      // Print
      for (int row=0; row<matrix.length; row++) {
         System.out.printf ("row %2d:  ", row+1);
         for (int col=0; col<matrix[row].length; col++) {
            System.out.printf ("%2d ", matrix[row][col]);
         }
         System.out.println ();
      }
   }

   /*
     Multiply two matrices together assuming their sizes are compatible. 
     If m1 is rectangluar, nxm matrix, and m2 is rectangular, mxp matrix,
     then the resulting matrix is a rectangular, nxp matrix.
   */
   public static int[][] matrixMultiply (final int[][] m1, final int[][] m2) {

      // Create a matrix to hold the result.  (Java ensures
      // that the new matrix is initialized to zero.)
      final int [][] result = new int [m1.length][m2[0].length];

      for (int i=0; i<m1.length; i++) {
         assert m1[i].length == m2.length;
         for (int j=0; j<m2.length; j++) {
            assert result[i][j] == 0;
            for (int k=0; k<m1[i].length; k++) {
               result[i][j] += m1[i][k] * m2[k][j];
            }
         }
      }

      return result;
   }
}