Skip to content
Advertisement

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:

JavaScript

And this is the method that I built to calculate the column sum:

JavaScript

Unfortunately, I receive an ArrayIndexOutOfBoundsException every time I run the code.

I can’t figure where my mistake is.

Advertisement

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.

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement