[英]How to create a two dimensional array from two one dimensional arrays and perform calculations
[英]How to add integers from one two dimensional array and create a new two dimensional array
我正在尝试解决一个问题,其中一个二维数组 (A) 是
1 1 0
1 1 0
1 1 0
得到的二维数组(B)是
1 2 2
2 4 4
3 6 6
B 中的每个点都是 A 中相应条目的总和,加上它左侧和上方的所有条目。
这是我到目前为止所做的
public static void main(String[] args)
{
int[][] arrA = { { 1, 1,0 }, { 1, 1,0 },{ 1, 1,0 } };
int[][] arrB = new int [3] [3];
for (int i = 0; i < arrA.length; i++) {
for (int j = 0; j < arrA.length; j++) {
System.out.print(arrA[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int r=0; r<arrB.length; r++) {
for(int c=0; c<arrB[r].length; c++) {
arrB[r][c] = r * c;
}
}
for(int r=0; r < arrB.length; r++) {
for(int c=0; c < arrB[r].length; c++) {
// if((r==0 || r==(arrA.length-1)) || (c==0 || c==(arrA.length-1)) )
arrB[r][c] = r+c;
System.out.print(arrB[r][c]+" ");
}
System.out.println();
}
}
}
我得到的答案是
0 1 2
1 2 3
2 3 4
我的问题是如何在数组 B 中获得正确的数字。我错过了什么代码?
B
每个值可以计算为:
B(i,j) = B(i-1,j-1) + B((i-1,j) - (i-1,j-1)) + A(i,j) + B((i,j-1)-(i-1,j-1))
这是因为:
对角线值 (i-1,j-1)是 (i,j) 的所有左侧和顶部值的总和,不包括直接顶部和左侧值。
左值 (i, j-1)是直接左值 + 对角线值的总和。
最高值 (i-1,j)是直接最高值 + 对角线值的总和。
所以,通过结合这 3 个值和当前元素,我们得到 B(i,j) 的值
这是更新的代码:
public static void main(String args[]) {
int[][] arrA = { { 1, 1,0 }, { 1, 1,0 },{ 1, 1,0 } };
int [][]B = new int [3][3];
int diag, i, j,top,left;
int len = arrA.length;
int bredth = arrA[0].length;
for( i=0;i<len;i++){
for( j=0;j<bredth;j++) {
diag = 0; top=0; left=0;
if(i-1>=0 && j-1>=0) {
diag = B[i-1][j-1];
}
if(i-1>=0) {
top = B[i-1][j];
}
if(j-1>=0) {
left = B[i][j-1];
}
B[i][j] = diag + arrA[i][j] + (top-diag) + (left-diag);
}
}
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
System.out.print(B[i][j]);
}
System.out.println();
}
}
您的代码问题在于您只是添加indexes
而不考虑values
。 但是根据您的问题,B 的每个值都应等于sum of corresponding entry in A, plus all entries to the left and above it
for(int r=0; r < arrB.length; r++) {
for(int c=0; c < arrB[r].length; c++) {
// if((r==0 || r==(arrA.length-1)) || (c==0 || c==(arrA.length-1)) )
arrB[r][c] = r+c; //Here `r` and `c` are just indexes value not actual value
System.out.print(arrB[r][c]+" ");
}
System.out.println();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.