Home > Mobile >  JavaScript take sum of diagonals of nested array with varying lengths
JavaScript take sum of diagonals of nested array with varying lengths

Time:01-18

I have a nested array where each array is one less in length than the array prior. I want to take the sum of elements diagonally and can't figure out how.

Here is a table representation of what I'm trying to do:

Table

In JavaScript the nested array is as follows:

let outArr = [];
const intArr= [0,2,4,6,8,10];
for (let i = intArr.length; i >0; i--) {
  outArr.push(intArr.slice(0,i));
}

I want my result array to be [0,2,6,12,20,30]. Do I use a triple nested loop? One for the output array and then two loops for the inner/outer array?

CodePudding user response:

You can iterate over the array once, keeping track of the current cumulative sum and adding it to the array on each iteration. (Note that the diagonal sums here are just the prefix sums of the array.)

let outArr = [];
const intArr= [0,2,4,6,8,10];
let curr = 0;
for (const x of intArr) outArr.push(curr  = x);
console.log(outArr);

CodePudding user response:

const array1 = [ 0, 2, 4, 6, 8, 10 ];
const array2 = [ 0, 2, 4, 6, 8 ];
const array3 = [ 0, 2, 4, 6 ];
const array4 = [ 0, 2, 4 ];
const array5 = [ 0, 2 ];
const array6 = [ 0 ];

const sum0 = array1[0];
const sum1 = array1[1]   array2[0];
const sum2 = array1[2]   array2[1]   array3[0];
const sum3 = array1[3]   array2[2]   array3[1]   array4[0];
const sum4 = array1[4]   array2[3]   array3[2]   array4[1]   array5[0];
const sum5 = array1[5]   array2[4]   array3[3]   array4[2]   array5[1]   array6[0];

const result = [
  sum0,
  sum1,
  sum2,
  sum3,
  sum4,
  sum5 ];

console.log(result);

CodePudding user response:

  • Get last elements of the array, on first index insert first one in result array and from next index add lastly inserted value from result and current value.

function getDiagonalSum(arr) {
  const lastArrays = [];
  const result = [];
  arr.forEach(currentArray => {
    lastArrays.push(currentArray[currentArray.length - 1]);
  });

  for (let i = 0; i < lastArrays.length; i  ) {
    if (i === 0) {
      result.push(lastArrays[i])
    } else {
      let total = lastArrays[i]   result[i - 1];
      result.push(total);
    }
  }
  return result;
}
const arr = [
  [1, 2, 3],
  [1, 2],
  [1]
];
const result = getDiagonalSum(arr);
console.log(result);
console.log("Your array input...")
const userArray = [
  [0, 0, 0, 0, 0, 0],
  [2, 2, 2, 2, 2],
  [4, 4, 4, 4],
  [6, 6, 6],
  [8, 8],
  [10]
];
const userResult = getDiagonalSum(userArray);
console.log(userResult);

CodePudding user response:

You basically need to get the indexes that give you the diagonal values. Keep two counters and increase one and decrease one and do it within bounds for each iteration.

As per your code if intArr is the nested array with all rows, then this would return you the diagonal sums.

let finalArr = [];
for (let i = 0; i <intArr.length; i  ) {
  let temp = 0, k=i;
  for(let j=0;j<=i;j  ){
    temp  = outArr[j][k--];
  } 
  finalArr.push(temp);
}

There is also a way easier way to do this if you don't want to work with the nested array since this is essentially the cumulative sum, so you don't need the nested array.

let intArr= [0,2,4,6,8,10];
let cumulative = 0, finalArr = [];;
for (let x of intArr) {
   finalArr.push(cumulative  = x);
}

CodePudding user response:

let inputArr=[]; let sumEntry =[]
       
       
        inputArray.reverse().forEach((subArr)=>{
       sumEntry.push((subArr.reduce((l,r)=>l r,0));
        });
inputArray.reverse().push(sumEntry);
  • Related