How to calculate RECURSIVELY 2D array column in Java

Tags: , , ,



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.

I can’t figure where my mistake is.

Answer

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

if (tempCol > maxCol)
            colIndex=j;


Source: stackoverflow