Matrix.java

Download
1/*2 * Matrix.java3 *4 * Computer Science S-225 */6 7/**8 * Matrix operations using square 2-dimensional integer arrays9 *10 * The multiplication algorithm provided here is not the fastest known.11 * In 1969, Volker Strassen invented a more complex algorithm that takes fewer12 * steps for large matrices. Each decade since, faster methods were found.13 */14public class Matrix {15 16    /**17     * Given two square matrices A and B, compute the product A*B.18     */19    public static int[][] mult(int[][] A, int[][] B) {20        int n = A.length;21        int[][] result = new int[n][n];22 23        for (int row = 0; row < n; row++) {24            for (int col = 0; col < n; col++) {25                int sum = 0;26                for (int i = 0; i < n; i++) {27                    // In terms of n, how many times does this line run?28                    sum += A[row][i] * B[i][col];29                }30                result[row][col] = sum;31            }32        }33 34        return result;35    }36 37    public static void print(int[][] arr, char name) {38        int n = arr.length;39 40        System.out.print("   ┌");41        for (int i = 0; i < n; i++) {42            System.out.print("    ");43        }44        System.out.println(" ┐");45 46        for (int row = 0; row < n; row++) {47            if (row == 0) {48                System.out.printf("%c: │", name);49            } else {50                System.out.print("   │");51            }52 53            for (int col = 0; col < n; col++) {54                System.out.printf(" %2d ", arr[row][col]);55            }56            System.out.println(" │");57        }58 59        System.out.print("   └");60        for (int i = 0; i < n; i++) {61            System.out.print("    ");62        }63        System.out.println(" ┘");64    }65 66    public static void main(String[] args) {67        int[][] A = {68            {1, 2},69            {3, 4}70        };71 72        int[][] B = {73            {0, 1},74            {1, 2}75        };76 77        print(A, 'A');78        print(B, 'B');79 80        int[][] C = mult(A, B);81        print(C, 'C');82    }83}