递归矩阵Java方法繁殖? [英] Java method for recursive matrix multiply?
问题描述
所以基本上,我想要做的就是让这需要2矩阵作为参数,并且将它们相乘的方法。这是一所学校的任务,和Im要求用递归分而治之,以解决这个问题。这是我的code迄今:
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;
}
}
我没有完成的code,因为我遇到了一个问题pretty快。我不能设置 C [0] [0]
到钙(smalla11,smallb11)
,因为它需要一个int,而钙
方法返回一个INT [] []。我其实不知道在这一点上做的。有时候,我会想只返回一个int值,不过后来我想返回子矩阵,最后全矩阵。没有任何人有任何建议,无论是在如何修理这个问题的回报,或者甚至对如何写code这样的计划?
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?
推荐答案
您正试图存储2维数组(从计算的结果(smalla11,smallb11))到一个单一的元素C [0,0]。 C已经已经被宣布为一个二维数组。你是故意想结果存储在一个单一的点0,0?
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?
这会做你需要什么?
c = calc(smalla11, smallb11);
这使我的大脑受到伤害,但它的乐趣! :)
This makes my brain hurt, but it's fun! :)
这篇关于递归矩阵Java方法繁殖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!