diff --git a/serie1/Matrix.java b/serie1/Matrix.java new file mode 100644 index 0000000000000000000000000000000000000000..82afa1fc94094a3eb33eb5ff440dd13e4765755b --- /dev/null +++ b/serie1/Matrix.java @@ -0,0 +1,56 @@ +public class Matrix { + + public static void printMatrix(int[][] mat) { + for (int i = 0; i < mat.length; i++) { + for (int j = 0; j < mat[i].length; j++) { + System.out.printf("%d ", mat[i][j]); + } + System.out.println(); + } + } + + public static int[][] mul(int[][] lhs, int[][] rhs) { + if (lhs[0].length != rhs.length) { + throw new RuntimeException("y axis of lhs doesn't match the x axis of rhs, multiplication cannot be done"); + } + + int[][] res = new int[lhs.length][rhs[0].length]; + + for (int i = 0; i < lhs.length; i++) { + for (int j = 0; j < rhs[i].length; j++) { + for (int k = 0; k < rhs.length; k++) { + + res[i][j] += lhs[i][k] * rhs[k][j]; + + } + } + } + + return res; + } + + public int[][] add(int[][] lhs, int[][] rhs) { + if (lhs.length != rhs.length || lhs[0].length != rhs[0].length) { + throw new RuntimeException("y axis of lhs doesn't match the x axis of rhs, multiplication cannot be done"); + } + + int[][] res = new int[lhs.length][lhs[0].length]; + + for (int i = 0; i < res.length; i++) { + for (int j = 0; j < res[i].length; j++) { + res[i][j] = lhs[i][j] + rhs[i][j]; + } + } + + return res; + } + + public static void main(String[] args) { + int[][] mat1 = new int[3][5]; + int[][] mat2 = new int[5][4]; + + int res[][] = mul(mat1, mat2); + + printMatrix(res); + } +}