/*
 * Matrix.java
 *
 * Computer Science E-22
 */

/**
 * Matrix operations using square 2-dimensional integer arrays
 *
 * The multiplication algorithm provided here is not the fastest known.
 * In 1969, Volker Strassen invented a more complex algorithm that takes fewer
 * steps for large matrices. Each decade since, faster methods were found.
 */
public class Matrix {

    /**
     * Given two square matrices A and B, compute the product A*B.
     */
    public static int[][] mult(int[][] A, int[][] B) {
        int n = A.length;
        int[][] result = new int[n][n];

        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                int sum = 0;
                for (int i = 0; i < n; i++) {
                    // In terms of n, how many times does this line run?
                    sum += A[row][i] * B[i][col];
                }
                result[row][col] = sum;
            }
        }

        return result;
    }

    public static void print(int[][] arr, char name) {
        int n = arr.length;

        System.out.print("   ┌");
        for (int i = 0; i < n; i++) {
            System.out.print("    ");
        }
        System.out.println(" ┐");

        for (int row = 0; row < n; row++) {
            if (row == 0) {
                System.out.printf("%c: │", name);
            } else {
                System.out.print("   │");
            }

            for (int col = 0; col < n; col++) {
                System.out.printf(" %2d ", arr[row][col]);
            }
            System.out.println(" │");
        }

        System.out.print("   └");
        for (int i = 0; i < n; i++) {
            System.out.print("    ");
        }
        System.out.println(" ┘");
    }

    public static void main(String[] args) {
        int[][] A = {
            {1, 2},
            {3, 4}
        };

        int[][] B = {
            {0, 1},
            {1, 2}
        };

        print(A, 'A');
        print(B, 'B');

        int[][] C = mult(A, B);
        print(C, 'C');
    }
}
