Sum integers in 2d array using recursion?

I need help with this problem. I have to sum all the integers in a 2d array using recursion. Below is what I managed to do on my own, but I'm stuck. This code generates a sum of 14, which should be equal to 18.

public class tablerecursion {
    public static void main(String[] args) {
        int[][] tabell = new int[][] { { 1, 2, 3 }, { 3, 2, 1 }, { 1, 2, 3 } };
        int sum = rec(tabell, 2, 2);
        System.out.println(sum);
    }

    static int rec(int[][] table, int n, int m) {
        if (m == 0)
            return table[n][0];
        if (n == 0)
            return table[0][m];
        System.out.println("n:" + n + "  m:" + m);

        return rec(table, n - 1, m) + rec(table, n, m - 1);
    }
}

Any suggestions? Is the base case wrong? Or the wrong recursion method?

+3
source share
6 answers

I would solve this using two functions. First, create a function that can recursively sum one (1d) array. Writing a function that recursively sums the previous function over an external array.

, [N] . .

+3

.

14,

f (2,2) = f (2,1) + f (1,2) = (f (2,0) + f (1,1)) + (f (1,1) + f ( 0,2))

f (0,2) - , 3 f (0,2) - , 1 f (1,1) = f (0,1) + f (1,0) = 2 + 3 = 5

, 3 + 1 + 5 + 5 = 14

- :

2x2, (x, y) (z, w), :

  xxxxxxxxxx
  xxxxxxxxxx
  xxxxxxxxxx
  yyyyyyyyyN
  • , , (xxxx-s ) , (x, y) - (z, 2-1).

  • , LAST ( - yyyyy-s ) , (x, w) - (z-1, w)

  • (z, w)

  • : y > w ( ), ; x

, . , " ", , , .

+2

1D- , 2D-

2D- 2D- . , , 1 × 1 2D-, .

, 2 ^ m x 2 ^ m; - , Nx1 1xN, . , 1D-.

0

. , , , :

public static void Main()
{
        var a = new int[][] {  new int[] {1,2,3},
                               new int[] {3,2,1},
                               new int[] {1,2,3}  }; 
        int result = a.Sum(row => row.Sum());
        Console.WriteLine(result);
}

, .

0

. java- , , . .

public static long countSum (int[][] matrix) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return 0;
    }
    return countSum (matrix, 0, 0, 0, matrix.length, matrix[0].length);
}

private static long countSum (int[][] matrix, long acc, int curI, int curJ, int maxI, int maxJ) {
    if (curI >= maxI) {
        return acc;
    }
    if (curJ >= maxJ) {
        return countSum(matrix, acc, curI + 1, 0, maxI, maxJ);
    }
    return countSum(matrix, acc + matrix[curI][curJ], curI, curJ + 1, maxI, maxJ);

}
0
public int sumarmatriz(int matriz[][],int i,int j)
{
    if(i==0 && j==0){
        return matriz[i][j];
    }
    else if(j==0){
        return sumarmatriz(matriz,i-1,matriz.length-1)+matriz[i][j];
    }
    else{
        return sumarmatriz(matriz,i,j-1)+matriz[i][j];
    }
}
0

Source: https://habr.com/ru/post/1764247/


All Articles