Multiply two matrices using 2D arrays (checking that the dimensions are compatible) and print the result row by row.
Solution
Main.java
import java.util.Arrays;
public class Main {
static int[][] multiply(int[][] a, int[][] b) {
if (a[0].length != b.length) throw new IllegalArgumentException("incompatible sizes");
int n = a.length, m = b[0].length, k = b.length;
int[][] c = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
for (int x = 0; x < k; x++) c[i][j] += a[i][x] * b[x][j];
return c;
}
public static void main(String[] args) {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
int[][] b = {{7, 8}, {9, 10}, {11, 12}};
for (int[] row : multiply(a, b)) System.out.println(Arrays.toString(row));
try { multiply(a, a); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
}
Output Verified by compiling and running
[58, 64]
[139, 154]
incompatible sizes
Each result cell is the dot product of a row of a and a column of b; the inner dimension must match.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!