简体   繁体   English

如何在 Java 中计算 RECURSIVELY 2D 数组列

[英]How to calculate RECURSIVELY 2D array column in Java

I am stuck with a homework question for something fairly stupid.我被一个相当愚蠢的家庭作业问题困住了。

The mission is to find the smallest column sum on a 2D array and return it's index.任务是在二维数组上找到最小的列总和并返回它的索引。 No loops allowed, only recursion.不允许循环,允许递归。

I managed the code, but I'm stuck with the simple task of calculating the column itself.我管理了代码,但我坚持计算列本身的简单任务。

This is the code I wrote so far:这是我到目前为止编写的代码:

public static int maxSumCol(int[][] a) {
        int maxCol=calculateCol(a, 0, 0);
        int colIndex=0;
        return maxSumCol(a, 0, 0, maxCol, colIndex);
    }
    private static int maxSumCol(int[][] a, int i, int j, int maxCol, int colIndex) {
        if (j<a.length){
            int tempCol=calculateCol(a, i, j);
            if (tempCol > maxCol)
                colIndex=j;
            return maxSumCol(a, i, j+1, maxCol, colIndex);   
        }
        return colIndex;
    }

And this is the method that I built to calculate the column sum:这是我为计算列总和而构建的方法:

   private static int calculateCol(int[][] a, int row, int col){
         if (row<=a.length-1)
             return a[row][col] + calculateCol(a, row+1, col);
         return 0;
    }

Unfortunately, I receive an ArrayIndexOutOfBoundsException every time I run the code.不幸的是,每次运行代码时我都会收到一个ArrayIndexOutOfBoundsException

I can't figure where my mistake is.我想不出我的错误在哪里。

What I can see from your post, there are two problems.我从你的帖子中看到,有两个问题。

First, when you calculate the sum of the columns you only check if the column index is less than the length of the outer matrix but this is the number of rows, not columns.首先,当您计算列的总和时,您只检查列索引是否小于外部矩阵的长度,但这是行数,而不是列数。

if (j<a.length){
    int tempCol=calculateCol(a, i, j);

The second is that when you found a column with greater sum than the one you have store previously, you only update the colIndex but not the maxcol variable where you store the actual value of the sum第二个是,当您发现一列的总和大于您之前存储的列时,您只更新 colIndex 而不是存储总和实际值的 maxcol 变量

if (tempCol > maxCol)
            colIndex=j;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM