Calculate the sum of elements in a matrix diagonally
I'm creating a function sum_diagonal(arr) to calculate the sum of elements in a matrix diagonally but when it reaches the center, the element is repeating.
for example:
2 6 4
1 3 5
6 2 2
Execution: 2+4+3+3+6+2
how do I get number 3 to appear only once?
3 Replies
You could do something like this
I'm using only 1 loop and get the fist and last index of the sub array, next iteration the 2nd and 2nd last, etc... when the indices do not equal each other, add both, other wise only 1
for fun this one as well, same logic, but with reduce and as oneliner (don't use in real life)
i % subarray.length
, assuming all subarrays are the same length?I tested mine on 2x2 and 4x4 matrices and it worked but only I had this issue on 3x3. After testing @markboots. 's answer it actually worked for all sizes. Thanks!