I need some help with this problem. I have to sum all integers in a 2d array using recursion. Below is what I have managed to do on my own, but I'm stuck. This code generates the sum 14, which should be 18.
public class tablerecursion {
public static void main(String[] args) {
int[][] tabell = new int[][] { { 1, 2开发者_Go百科, 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 is the recursive method wrong?
I would solve this using two functions. First create a function that can recursively sum a single (1d) array. The write a function that recursively sums the previous function over the outer array.
Remember that table[N] is itself an array. You don't have to access it all in one go.
Your recursion logic is wrong.
Your get 14 because you call
f(2,2)=f(2,1) + f(1,2)= (f(2,0)+f(1,1)) + (f(1,1)+f(0,2))
f(0,2) is your base case, 3 f(0,2) is your base case, 1 f(1,1) = f(0,1)+f(1,0)=2+3=5
So the sum is 3+1+5+5=14
The proper logic to recurse this is as a single recursive function:
A sum of an 2x2 array starting with coordinates (x,y) and ending with (z,w) is a sum of 3 things:
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
yyyyyyyyyN
A sum of an array consisting of ALL the lines except the last one (xxxx-s in the example above) So (x,y) to (z,2-1).
A sum of an array consiting of LAST line (except lower right corner - yyyyy-s in example) So, (x,w) to (z-1,w)
An the number at coordinates (z,w)
The base cases are, if y>w (zero lines), the sum is zero; if x
This is really a DOUBLE recursion, ideally. One is recursively compute a sum of all lines by using a helper "add a line" function - which of course is also recursively implemented.
A couple of other answers suggest using a 1D routine to sum the column and the row adjacent to an element in the corner of the 2D array
BUT
It would be just as valid to cut your 2D array into four smaller 2D arrays, and recurse that way. The stopping condition is of course when the input is a 1x1 2D array, where the answer is trivial.
follow up
This runs into a snag unless the array dimensions are 2^m x 2^m ; anything else and sooner or later you encounter an Nx1 or 1xN input, and you simply cannot cut this into four sub-arrays. So you end up having to deal with 1D input anyway.
See here is what I would turn in, and point out that a recursive solution doesn't apply:
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);
}
It is better to be right than simply considered right.
Here is an example of possible solution. If java compiler could optimize tail recursion then it would be as efficient as iterative solution. Now it eats stack very agressively.
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);
}
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];
}
}
If you want to access it all in one go, I think this method is what you need:
public class Array {
public static void main(String[] args){
int[][] A = {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}};
System.out.print(TwoDSum(A,4,4));
}
public static int TwoDSum(int A[][], int n,int m) {
if(n==1 && m==1) return A[0][0];
if(m==0){
n--;
m=A[n].length;
}
return TwoDSum(A,n,m-1)+A[n-1][m-1];
}
}
精彩评论