How to sum specific elements in an array?

Viewed 187

I am trying to manipulate an array. For each operation, I need to add a value to each the array element between two given indices, inclusive. Here is one example:

0 1 100  // From index 0 to 1, add 100
1 4 100  // From index 1 to 4, add 100
2 3 100  // From index 2 to 3, add 100

// Expected Result:
[100, 200, 200, 200, 100]

// Explanation:
[100, 100] // After the first update.
[100, 200, 100, 100, 100] // After the second update.
[100, 200, 200, 200, 100] // After the third update.

And this was as far as I got:

function arrayManipulation(n, queries) {
  let newArr = [];
  for (let i = 0; i < queries.length; i++) {
    let indexIni = queries[i][0];
    let indexEnd = queries[i][1];
    let indexSum = queries[i][2];

    for (indexIni; indexIni < indexEnd; indexIni++) {
      console.log(indexIni, indexEnd, indexSum);
      newArr.splice(indexIni, 0, indexSum);
    }
  }
  console.log(newArr);
}

let n1 = 5;
let queries1 = [
  [0, 1, 100],
  [1, 4, 100],
  [2, 3, 100]
];
arrayManipulation(n1, queries1);

What I was trying to do was work on top of the second parameter of splice() so that I could somehow add it up to the number I was going to input.

The way I'm trying, is it possible? Or is there a simpler method?

2 Answers

1) loop should go upto

indexIni <= indexEnd

2) Iterating from the start and checking if any number is present on that particular index or not. If it does then add the indexSum else set the value as indexSum.

function arrayManipulation(n, queries) {
  let newArr = [];
  for (let i = 0; i < queries.length; i++) {
    let [indexIni, indexEnd, indexSum] = queries[i];

    for (indexIni; indexIni <= indexEnd; indexIni++) {
      if (newArr[indexIni]) {
        newArr[indexIni] += indexSum;
      } else {
        newArr[indexIni] = indexSum;
      }
    }
  }
  console.log(newArr);
}

let n1 = 5;
let queries1 = [
  [0, 1, 100],
  [1, 4, 100],
  [2, 3, 100],
];
arrayManipulation(n1, queries1);

Using forEach and Array.from

function arrayManipulation(data) {
  const res = [];
  data.forEach(([start, end, value]) => {
    Array.from({ length: end - start + 1 }, (_, i) => start + i).forEach(
      (index) => (res[index] = (res[index] ?? 0) + value)
    );
  });
  return res;
}

const data = [
  [0, 1, 100],
  [1, 4, 100],
  [2, 3, 100],
];

console.log(arrayManipulation(data));

Related