diff --git a/2020/15/solution1.js b/2020/15/solution1.js new file mode 100644 index 0000000..260302f --- /dev/null +++ b/2020/15/solution1.js @@ -0,0 +1,36 @@ +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); diff --git a/2020/15/solution2.js b/2020/15/solution2.js new file mode 100644 index 0000000..54046fa --- /dev/null +++ b/2020/15/solution2.js @@ -0,0 +1,41 @@ +// TODO: optimization needed + +// const input = "0,3,6"; +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; +let lastLog = new Date(); +while (turn <= 30000000) { + if (typeof memory[lastNum] === "undefined") { + num = 0; + } else { + num = turn - 1 - memory[lastNum]; + } + + const now = new Date(); + if (now - lastLog > 5000) { + console.log(`Turn ${turn.toLocaleString()}, num: ${num}`); + lastLog = now; + } + + memory[lastNum] = turn - 1; + lastNum = num; + turn += 1; +} + +console.log("Solution:", num);