Matrix Class
Completed
Write an immutable Matrix class with add, multiply, transpose and toString. Read two 2×2 matrices and print A+B, A×B and Aᵀ separated by -- lines.
Input
Four lines: two rows of A, two rows of B.
Output
The three results.
Example
Input
1 2 3 4 5 6 7 8
Output
6 8 10 12 -- 19 22 43 50 -- 1 3 2 4
Editor
Java
Hints
Each operation builds and returns a new Matrix.
Solution explanation
Immutable value classes are easy to reason about: an operation never changes its inputs.
Show solution
import java.util.Scanner;
final class Matrix {
private final int[][] m;
Matrix(int[][] m) {
this.m = m;
}
Matrix add(Matrix o) {
int[][] r = new int[m.length][m[0].length];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[0].length; j++)
r[i][j] = m[i][j] + o.m[i][j];
return new Matrix(r);
}
Matrix multiply(Matrix o) {
int[][] r = new int[m.length][o.m[0].length];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < o.m[0].length; j++)
for (int k = 0; k < o.m.length; k++)
r[i][j] += m[i][k] * o.m[k][j];
return new Matrix(r);
}
Matrix transpose() {
int[][] r = new int[m[0].length][m.length];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[0].length; j++)
r[j][i] = m[i][j];
return new Matrix(r);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
sb.append(j > 0 ? " " : "").append(m[i][j]);
}
if (i < m.length - 1) sb.append('\n');
}
return sb.toString();
}
}
public class Main {
static Matrix read(Scanner sc) {
int[][] m = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
m[i][j] = sc.nextInt();
return new Matrix(m);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Matrix a = read(sc), b = read(sc);
System.out.println(a.add(b));
System.out.println("--");
System.out.println(a.multiply(b));
System.out.println("--");
System.out.println(a.transpose());
}
}