猿问

java - 如何通过在java中的空位置添加零来使两个不相等的二维数组相等?

假设我的矩阵 A 的顺序为 3 x 2,矩阵 B 的顺序为 2 x 4。我得到的矩阵应该是 3 x 4 的顺序,它应该包含矩阵 A 和矩阵 B 的相加。为了实现我必须首先通过附加必要的零来使矩阵 A 和矩阵 B 的大小相等(两者都应该是 3 x 4)。


例子 :-


int[][] a = { {1,0}, {1,1}, {1,0} }; 

int[][] b = { {1,1,0,1}, {1,1,1,1} }; 

sumArray(a,b) 将返回: { {2,1,0,1}, {2,2,1,1}, {1,0,0,0} }


我试过的是。(ans.length 表示结果矩阵长度)


for(int i =0;i<ans.length;i++)

  {

    for(int j=0;j<ans[i].length;j++)

    {

     if(arr1[i][j] == null)

     {

       arr1[i][j]= 0;

     }

      if(arr2[i][j] == null)

     {

       arr2[i][j]= 0;

     }

    }

  }


素胚勾勒不出你
浏览 151回答 2
2回答

潇潇雨雨

首先,您必须找到输出数组的大小。int h = a.length>b.length?a.length:b.length;int w = a[0].length>b[0].length?a[0].length:b[0].length;int[][] result = new int[h][w];然后做你的任务。for(int i = 0; i<result.length; i++){&nbsp; &nbsp; for(int j = 0; j<result[i].length; j++){&nbsp; &nbsp; &nbsp; &nbsp; if(i<a.length && j < a[i].length){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[i][j] += a[i][j];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(i<b.length && j < b[i].length){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[i][j] += b[i][j];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}return result;

慕桂英3389331

使用此代码。只需使尺寸标识部分动态化import java.util.Arrays;public class Main{&nbsp; public static void main (String[]args)&nbsp; {&nbsp; &nbsp; System.out.println ("Hello World");&nbsp; &nbsp; int m1 = 3, n1 = 1, m2 = 2, n2 = 4; // m1 and n1 are matrix 'x' dimensions and m2 & n2 are natrix 'y' dimensions&nbsp; &nbsp; int x[][] = {&nbsp; &nbsp; &nbsp; {1},&nbsp; &nbsp; &nbsp; {2},&nbsp; &nbsp; &nbsp; {3}&nbsp; &nbsp; };&nbsp; &nbsp; int y[][] = {&nbsp; &nbsp; &nbsp; {1, 2, 1, 2},&nbsp; &nbsp; &nbsp; {1, 2, 1, 2}};&nbsp; &nbsp; &nbsp;int op[][] = new int[m1][n2];&nbsp; &nbsp; &nbsp;for (int[] row: op)// filling empty matrix with zeroes&nbsp; &nbsp; &nbsp;Arrays.fill(row, 0);&nbsp; &nbsp; for (int i = 0; i < m1; i++)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; for (int j = 0; j < n1; j++)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; op[i][j] = x[i][j];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; int op2[][] = new int[m1][n2];&nbsp; &nbsp; for (int[] row: op2)// filling empty matrix with zeroes&nbsp; &nbsp; &nbsp;Arrays.fill(row, 0);&nbsp; &nbsp; for (int i = 0; i < m2; i++)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; for (int j = 0; j < n2; j++)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; op2[i][j] = y[i][j];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; for(int i=0;i<m1; i++)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j=0;j<n2;j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print((op[i][j]+op2[i][j])+" ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; }&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答