const input = "9,3,1,0,8,4"; const start = input.split(","); const memory = {}; let turn = 1; let lastNum = null; for (const num of start) { if (lastNum !== null) { memory[lastNum] = turn - 1; } lastNum = num; console.log(`Turn ${turn}: ${num}`); turn += 1; } let num; while (turn <= 2020) { if (typeof memory[lastNum] === "undefined") { num = 0; } else { num = turn - 1 - memory[lastNum]; } console.log( `Turn ${turn}: ${num}${ num !== 0 ? ` (${turn - 1} - ${memory[lastNum]})` : "" }` ); memory[lastNum] = turn - 1; lastNum = num; turn += 1; } console.log("Solution:", num);