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?
function sum_diagonal(arr) {
let left_diagonal = 0, right_diagonal = 0;
let output = "";
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i == j) {
left_diagonal += arr[i][j];
output += arr[i][j] + "+";
}
if((i + j) == (arr.length - 1)) {
right_diagonal += arr[i][j];
output += arr[i][j] + "+";
}
}
}
return output;
}
console.log(sum_diagonal(result));
function sum_diagonal(arr) {
let left_diagonal = 0, right_diagonal = 0;
let output = "";
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i == j) {
left_diagonal += arr[i][j];
output += arr[i][j] + "+";
}
if((i + j) == (arr.length - 1)) {
right_diagonal += arr[i][j];
output += arr[i][j] + "+";
}
}
}
return output;
}
console.log(sum_diagonal(result));
3 Replies
MarkBoots
MarkBoots2y ago
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
const result = [
[2, 6, 4],
[1, 3, 5],
[6, 2, 2]
];

function sum_diagonal(arr){
let sum = 0;
for(let i = 0; i < arr.length; i++){
const leftIndex = i;
const rightIndex = arr.length - 1 - i;
sum += arr[i][leftIndex];
if(leftIndex !== rightIndex) sum += arr[i][rightIndex];
}
return sum;
}
console.log(sum_diagonal(result)) // 17
const result = [
[2, 6, 4],
[1, 3, 5],
[6, 2, 2]
];

function sum_diagonal(arr){
let sum = 0;
for(let i = 0; i < arr.length; i++){
const leftIndex = i;
const rightIndex = arr.length - 1 - i;
sum += arr[i][leftIndex];
if(leftIndex !== rightIndex) sum += arr[i][rightIndex];
}
return sum;
}
console.log(sum_diagonal(result)) // 17
for fun this one as well, same logic, but with reduce and as oneliner (don't use in real life)
const sum_diagonal = arr => arr.reduce((s,a,i)=>(j=a.length-1-i,s+=a[i]+(i!==j?a[j]:0)),0)
const sum_diagonal = arr => arr.reduce((s,a,i)=>(j=a.length-1-i,s+=a[i]+(i!==j?a[j]:0)),0)
vince
vince2y ago
Could you also do something like i % subarray.length, assuming all subarrays are the same length? Last row wouldn't work since it would return 0 I believe
kooliris
koolirisOP2y ago
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!
Want results from more Discord servers?
Add your server