2个不同二维数组的总和

时间:2023-01-15
本文介绍了2个不同二维数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助编写一个方法来找出 2 个不同大小的二维数组的总和.

I need help writing a method to find out a sum of 2 different sized 2D arrays.

public static int[][] summary(int[][] tab1, int[][] tab2, int x) {
    int[][] finalTab = new int[4][5]; // I took sizes of bigger one
    if (x < 0) {
        for (int i = 0; i < finalTab.length - 1; i++) {
            for (int j = 0; j < finalTab[i].length - 1; j++) {
                finalTab[i][j] = tab1[i][j] + tab2[i][j];
                if (tab1[i][j] == 0) {
                    finalTab[i][j] = tab2[i][j];
                }
            }
        }
        for (int i = 0; i < finalTab.length; i++) {
            for (int j = 0; j < finalTab[i].length; j++) {
                System.out.print(" " + finalTab[i][j] + " ");
            }
            System.out.println();
        }
    }
    return finalTab;
}

输入是:

int[][] tab1 = {
        {2, 4, 6, 8},
        {2, 4, 6, 8},
        {2, 4, 6, 8}};

int[][] tab2 = {
        {1, 3, 5, 7, 9},
        {1, 3, 5, 7, 9},
        {1, 3, 5, 7, 9},
        {1, 3, 5, 7, 9}};

输出是:

 3  7  11  15  0 
 3  7  11  15  0 
 3  7  11  15  0 
 0  0  0  0  0 

输出应该是:

 3  7  11  15  9
 3  7  11  15  9
 3  7  11  15  9
 1  3  5  7  9

如何将0全部替换为tab2的索引对应的数字?

How can I replace all of 0 with numbers corresponding to the index of tab2?

推荐答案

你可以做得更通用

public static int[][] summary(int[][] tab1, int[][] tab2, int x) {
    int maxLenX = tab1.length > tab2.length ? tab1.length : tab2.length;
    int maxLenY = tab1[0].length > tab2[0].length ? tab1[0].length : tab2[0].length;
    int[][] finalTab = new int[maxLenX][maxLenY]; // i took sizes of bigger one
    if (x < 0) {
        for (int i = 0; i <= finalTab.length - 1; i++) {
            for (int j = 0; j <= finalTab[i].length - 1; j++) {
                if (i > tab1.length - 1 || j > tab1[i].length - 1) {
                    finalTab[i][j] = tab2[i][j];
                } else if (i > tab2.length - 1 || j > tab2[i].length - 1) {

                    finalTab[i][j] = tab1[i][j];
                } else {
                    finalTab[i][j] = tab1[i][j] + tab2[i][j];
                }
            }
        }
        for (int i = 0; i < finalTab.length; i++) {
            for (int j = 0; j < finalTab[i].length; j++) {
                System.out.print(" " + finalTab[i][j] + " ");
            }
            System.out.println();
        }
    }
    return finalTab;
}

所以你可以这样称呼它

summary(tab2, tab1, -1);

summary(tab1, tab2, -1);

这篇关于2个不同二维数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:MySQL 中 SUM 结果的数据类型 下一篇:读取输入,直到输入特定数字

相关文章

最新文章