Never saw syntax like that, why/how is this working. Solution for Euler18 from hints page

challenge link
I solved it, but my solution is heavy I guess.

So I am trying to reverse-engineer code from hints page.

First question: how loops work without {} brackets, I never saw that in curriculum(maybe I forgot but I don’t think so)

Second. When I added some logging like below it started throwing errors. I guess it connected to the first question.

function maximumPathSumI(triangle) {
  // Copy the triangle
  //   Note: not needed if we are ok with mutating the input
  const triangleCopy = triangle.map(row => [...row]);
  // Find max path
  for (let i = triangleCopy.length - 2; i >= 0; i--)
   console.log('to check outer loop'); //ADDED by me
   console.log(i, triangle[i]); //ADDED by me
    for (let j = 0; j <= i; j++)
      triangleCopy[i][j] +=
        Math.max(triangleCopy[i + 1][j], triangleCopy[i + 1][j + 1])
  return triangleCopy[0][0];
}




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

maximumPathSumI(testTriangle);

You can omit the {} only if the loop body is a single line.

1 Like

In JavaScript, if you omit the brackets on a for loop, it will only execute the statement immediately following the declaration of the for loop every iteration. The reason it broke when you added the log statement is because the i variable no longer exists for the statements that follow it - the scope of the for loop has ended.

This all applies to if statements as well.

2 Likes

I get it now, thanks. So all I needed to do is just add brackets.

1 Like

I finished reviewing this solution.
As far as I figured, the main trick here: to start building sums from the bottom of triangle, not from the top.

In my solution I was building sums from the top, and I needed to build all possible sums.

It that it? Or am I missing something?

Yup, the big trick is traversing the triangle the other direction

1 Like