I was working on Leetcode Problem 1770 and ran into some weird behavior that I'm hoping someone can help me understand.
It's a dynamic programming problem that requires you to instantiate a 2-dimensional array of length m
. Pretty straightforward.
What's weird is that my syntax for generating a 2D array causes the problem to fail, but an alternative syntax passes all tests. As far as I can tell the two lines output an identical result.
My syntax:
// const m = 3
let memo = new Array(m).fill(new Array(m).fill(-Infinity))
console.log({memo})
// stdout: {
// memo: [
// [ -Infinity, -Infinity, -Infinity ],
// [ -Infinity, -Infinity, -Infinity ],
// [ -Infinity, -Infinity, -Infinity ]
// ]
// }
Alternative syntax:
// const m = 3
let memo = Array.from(Array(m), () => Array(m).fill(-Infinity))
console.log({memo})
// stdout: {
// memo: [
// [ -Infinity, -Infinity, -Infinity ],
// [ -Infinity, -Infinity, -Infinity ],
// [ -Infinity, -Infinity, -Infinity ]
// ]
// }
To my eye the output of the two is exactly identical. Yet one passes all tests and what doesn't. What gives?