Method to solve a word search in Java using 2d arrays

I'm trying to create a method that will search through a 2d array of numbers. If the numbers add up to a certain sum, those numbers should remain and all of the other numbers should be changed to a 0. For example, if the desired sum is 7 and a row contains 2 5 1 2, the result should be 2 5 0 0 after the method is implemented. I have everything functioning but instead of keeping all of the numbers that add up to the sum, only the last number is retained. So, I am left with 0 5 0 0 . I think I need another array somewhere but not sure exactly how to go about implementing it. Any ideas?

Code :

public static int[][] horizontalSums(int[][] a, int sumToFind) {
int[][] b = new int[a.length][a[0].length];
int columnStart = 0;
while (columnStart < a[0].length) {
for (int row = 0; row < a.length; row++) {
int sum = 0;
for (int column = columnStart; column < a[row].length; column++) {
sum += a[row][column];
if (sum == sumToFind) {
b[row][column] = a[row][column];
}
}
}
columnStart++;
}
return b;
}

Re: Method to solve a word search in Java using 2d arrays

Can you explain the algorithm you are using for this program? What steps does the code need to take to get the desired results?

Re: Method to solve a word search in Java using 2d arrays

It need go through a horizontal array checking if consecutive numbers add up to a desired sum. If they do, those numbers remain, if they don't, the numbers become zeros.

Re: Method to solve a word search in Java using 2d arrays

Quote:

checking if consecutive numbers add up to a desired sum

Does that mean the code must restart the search when the sum gets too large? How will the code handle that? For example if the target is 7 and a row has: 4 5 5 2 there will need to be some restarts.

What steps must the code take to do this:* those numbers remain*

or this:* the numbers become zeros.*

Those are high level requirements for the program. What logic/steps does the code need to take to do them?

There are two arrays: a and b

how are they used?

Re: Method to solve a word search in Java using 2d arrays

if its 4 5 5 2. its supposed to add 4 and 5, then add 5 and 5, then and 5 and 2.

Re: Method to solve a word search in Java using 2d arrays

How will the code do that? What is the logic?

What does the code need to remember to be able to restart the summing for the next numbers in the row?

What should it do when some where in the search through the values in a row it finds a series of numbers with the right sum?

You should take a piece of paper and a pencil, write a series of numbers in a row and then work out the logic. Draw pointers under the numbers to represent the indexes into the array. Label them and see how the indexes need to be moved and used to solve the problem.