Why does my function change the array?

I’ve done project euler’s max triangle sum problem and I dont understand why it keeps changing the global variable, when i remove the function call all the tests pass, I mean, i created a copy of triangle and even tried using a for loop to push, why cant it be like C++ when you need reference to change it?? oof.
how do you make the function not change the global? var arr = triangle doesn’t seem to work either


function maximumPathSumI(triangle) {
var arr = [...triangle];
var arrLen = arr.length-2;
for(let i = arrLen; i >= 0; i--) {
  for(let j = i; j >= 0; j--) {
    arr[i][j] += Math.max(arr[i+1][j], arr[i+1][j+1]);
  }
}
return arr[0][0];
}

const testTriangle = [[3, 0, 0, 0],
                    [7, 4, 0, 0],
                    [2, 4, 6, 0],
                    [8, 5, 9, 3]];

maximumPathSumI(testTriangle)
console.log(testTriangle); /*[ [ 23, 0, 0, 0 ],
  [ 20, 19, 0, 0 ],
  [ 10, 13, 15, 0 ],
  [ 8, 5, 9, 3 ] ]*/

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Problem 18: Maximum path sum I

Link to the challenge:

it is creating a shallow copy, as in it is copying the outer array, but inside it there are still the references to the inner arrays

there are ways to do deeper copies, for example this works for a two levels array: copy = original.map(innerArr => [...innerArr])

6 Likes

Non-primative function args are like C++. Passing a variable that points to an array passes the reference to the array. Neither language passes a copy of an array. That would be very memory inefficient. This is one of the reasons why it’s good to think of ways to avoid consuming the inputs, because you often do not want to modify input arrays and copying can be expensive.

In this case, you could use a couple of auxiliary arrays to avoid modifying the input.

1 Like