问题
So basically, what I want to do is make a method that takes 2 matrices as arguments, and multiplies them. This is a school task, and Im asked to solve this by using recursive "Divide and Conquer". This is my code so far:
public class RecMult {
public int[][] calc(int[][] a, int[][] b) {
int n = a.length;
int[][] c = new int[n][n];
if (n == 1) {
c[0][0] = a[0][0] * b[0][0];
} else {
int sub = a.length / 2;
int[][] smalla11 = new int[sub][sub];
int[][] smalla12 = new int[sub][sub];
int[][] smalla21 = new int[sub][sub];
int[][] smalla22 = new int[sub][sub];
int[][] smallb11 = new int[sub][sub];
int[][] smallb12 = new int[sub][sub];
int[][] smallb21 = new int[sub][sub];
int[][] smallb22 = new int[sub][sub];
for (int i = 0; i < sub; i++) {
for (int j = 0; j < sub; j++) {
smalla11[i][j] = a[i][j];
smalla12[sub + i][j] = a[sub + i][j];
smalla21[i][sub + j] = a[i][sub + j];
smalla22[sub + i][sub + j] = a[sub + i][sub + j];
smallb11[i][j] = b[i][j];
smallb12[sub + i][j] = b[sub + i][j];
smallb21[i][sub + j] = b[i][sub + j];
smallb22[sub + i][sub + j] = b[sub + i][sub + j];
}
}
c[0][0] = calc(smalla11, smallb11);
}
return c;
}
}
I did not complete the code because I encountered a problem pretty fast. I'm not able to set c[0][0]
to calc(smalla11, smallb11)
because it takes an int, and the calc
method returns a int[][]. Im not actually sure what to do at this point. Sometimes, I would have wanted to return just a single int, but later I would want to return submatrices and at last the full matrix. Does anyone have any suggestions, either on how to "fix" this return issue, or maybe even a better idea on how to write the code for such a program?
回答1:
You're trying to store a 2 dimensional array (the results from calc(smalla11, smallb11)) into a single element c[0,0]. c has already been declared to be a 2 dimensional array. Are you intentionally trying to store the result in a single point 0,0?
Would this do what you need?
c = calc(smalla11, smallb11);
This makes my brain hurt, but it's fun! :)
来源:https://stackoverflow.com/questions/21416512/java-method-for-recursive-matrix-multiply