0

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.

0

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

This was indeed the mistake in my code and the answer. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.