1

I am looking for a function that can produce the nth line of Pascal's triangle. I've found several solutions online but I don't quite fully understand them. Could someone explain this code block? I don't understand why unshift method wouldn't just produce an array of 1s.

const getRow = rowIndex => {
    const res = []

    while (res.length <= rowIndex) {
        res.unshift(1)
        for(let i = 1; i < res.length - 1; i++) {
            res[i] += res[i + 1]
        }
    }

    return res
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • `res[i] += res[i + 1]` <= So what do you think this line is doing? – Taplar Feb 27 '20 at 18:49
  • I think i understand that that line is overwriting the values of res[i] but I don't understand why that loop starts before unshift is done. When i console logged everything out (& using 5 as my row#) it seems like the loop starts after the third 1 is unshifted into the empty array. – michellesokolov Feb 27 '20 at 19:02
  • Well, consider that your `for` loop will only execute once your array has (at least) 3 elements, as `1 < 2 - 1` would not be true. It will only be true for the first time once there are 3 elements. – Taplar Feb 27 '20 at 19:10
  • Each pass through the `while` loop adds '1' to the beginning of `res`, increasing it's length by 1. The `for` loop then adds the value of the element at `i + 1` to the the element at `i` if `i + 1` is within the bounds of the array. This goes until `res.length <= rowIndex`. – JDunken Feb 27 '20 at 19:10
  • okay I think I'm starting to understand this! the loop starts once `i < res.length - 1` is true. Thank you guys for the help! – michellesokolov Feb 27 '20 at 19:42

0 Answers0