# How to add elements of an array diagonally

2020-02-15 java arrays algorithm

I have an array:

``````1 2 3
4 5 6
7 8 9
``````

Now I want to add them side ways :

means

``````a) position (0,0) --> print 1
b) position (1,0) =4 --> (0,1) =2 ==> sum is 4 + 2 = 6 (print this)
c) position (2,0) = 7 --> (1,1) = 5 ==> (0,2) ==> 3 --> sum 7+5+3 = 15 (print this)
d) position (2,1) = 8 --> (1,2) = 6 --> sum = 8 + 6 = 14 (print this)
e) position (2,2) = 9 --> sum = 9(print this)
``````

How to do this in Java for a given array?

Start by pretending the array is bigger.

Then iterate the rows and sum the diagonal going up-right, skipping cells that don't actually exist.

``````1 2 3 . .     🡕 🡕 🡕 🡕 🡕
4 5 6 . .     🡕 🡕 🡕 🡕 .
7 8 9 . .     🡕 🡕 🡕 . .
. . . . .     🡕 🡕 . . .
. . . . .     🡕 . . . .
``````

So something like this (pseudo-code):

``````for (i = 0; i < width + height - 1; i++) {
sum = 0
for (j = i; j >= 0; j--)
if (j < height && i - j < width)
sum += grid[j][i - j]
print sum
}
``````

That works for rectangular grids as well as the square grids. The pretended grid will be square.

``````1 2 3 4 5 6 . .     🡕 🡕 🡕 🡕 🡕 🡕 🡕 🡕
2 3 4 5 6 7 . .     🡕 🡕 🡕 🡕 🡕 🡕 🡕 .
3 4 5 6 7 8 . .     🡕 🡕 🡕 🡕 🡕 🡕 . .
. . . . . . . .     🡕 🡕 🡕 🡕 🡕 . . .
. . . . . . . .     🡕 🡕 🡕 🡕 . . . .
. . . . . . . .     🡕 🡕 🡕 . . . . .
. . . . . . . .     🡕 🡕 . . . . . .
. . . . . . . .     🡕 . . . . . . .     // Sorry the font makes it look skewed
``````

Related