programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Need help with sums of rows and columns of two dimensional arrays

Greenhorn
Posts: 2
I have a two dimensional array that contains integers ranging from 1 to 9. What I'm trying to do is in each row go through it and add up each number to 20 and print out a new array with those numbers. If a number used makes it so that it does not equal 20 that number is now 0. for an example:

Input Array:
8 4 5 4 3 7 1 2 1 8
6 8 6 7 8 6 2 4 6 2

Horizontal sum output would be:
0 0 5 4 3 7 1 0 0 0
6 8 6 0 8 6 2 4 6 2

8 6 2 4 6 2 contains two overlapping sums that equal 20: 8 + 6 + 2 + 4 and 6 + 2 + 4 + 6 + 2

Input Array:
9 5
9 6
6 2
9 6
2 1
9 7
1 8
6 2
8 5
5 8

Vertical sum output would be:
0 5
0 6
0 2
9 6
2 1
9 0
1 0
6 0
8 0
5 0

I can't for the life of me think of an algorithm that would come up with a correct answer.

Bartender
Posts: 3304
86
• 1
Write down in words exactly how you solved it in the examples you showed - there's your algorithm.

Marshal
Posts: 57437
175
And welcome to the Ranch
There is a mistake in the first thing you wrote. You don’t have a 2D array; there ain’t no such critter in Java. You have an array of arrays, (which is actually better than a 2D array).

author
Sheriff
Posts: 23364
127

Andrew Harry wrote:
I can't for the life of me think of an algorithm that would come up with a correct answer.

Having read this topic three times, I still can't figure out what you are trying to say. Perhaps if you can better describe the algorithm, so that we can understand it, then they can be translated to pseudo code, which can be used to translate to actual code.

Henry

Henry Wong
author
Sheriff
Posts: 23364
127

Henry Wong wrote:

Andrew Harry wrote:
I can't for the life of me think of an algorithm that would come up with a correct answer.

Having read this topic three times, I still can't figure out what you are trying to say. Perhaps if you can better describe the algorithm, so that we can understand it, then they can be translated to pseudo code, which can be used to translate to actual code.

Ohhh.... I see.

The algorithm looks pretty straightforward. Start at index zero. At the current index, count forward until you either you get 20, or exceed 20. If you get 20, then mark the whole range (of all the involved numbers). And here is the trick, even though a number is marked, you don't get to skip it. You still need to only go one index at a time, as any number can be marked more than once, as part of different ranges.

Henry

Andrew Harry
Greenhorn
Posts: 2
Figured it out, thanks guys!

 It is sorta covered in the JavaRanch Style Guide.