From e0206bd8aefe1229c27295c752d308b6bd900474 Mon Sep 17 00:00:00 2001 From: legonzaur Date: Fri, 15 Dec 2023 11:41:45 +0100 Subject: [PATCH] 15 --- 15.1.ts | 3 ++- 15.2.ts | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 15.2.ts diff --git a/15.1.ts b/15.1.ts index 98eb289..071f8ac 100644 --- a/15.1.ts +++ b/15.1.ts @@ -15,4 +15,5 @@ const file = await open('./inputs/15'); for await (const line of file.readLines()) { console.log(line.split(',').map(getHash).reduce((acc, cur) => acc + cur, 0)) -} \ No newline at end of file +} +console.log(getHash('rn')) \ No newline at end of file diff --git a/15.2.ts b/15.2.ts new file mode 100644 index 0000000..cc52fe9 --- /dev/null +++ b/15.2.ts @@ -0,0 +1,52 @@ +import { open } from 'node:fs/promises'; + +function getHash(input: string) { + let curr = 0 + + for (var i = 0; i < input.length; i++) { + curr += input.charCodeAt(i) + curr *= 17 + curr %= 256 + } + return curr +} + +const boxes = new Array(256).fill([]).map(() => new Array()) as { label: string, focal: number }[][] +const file = await open('./inputs/15'); + +for await (const line of file.readLines()) { + + + const lenses = line.split(',') + lenses.forEach(l => { + // Remove + if (l.endsWith('-')) { + const label = l.slice(0, l.length - 1) + const box = getHash(label) + const index = boxes[box].findIndex(e => e.label === label) + if (index == -1) { + return + } + boxes[box].splice(index, 1) + } + + // Add or Replace + if (l.indexOf('=') !== -1) { + const [label, focal] = l.split('=') + const box = getHash(label) + const index = boxes[box].findIndex(e => e.label === label) + if (index == -1) { + boxes[box].push({ label, focal: Number(focal) }) + } else { + boxes[box][index].focal = Number(focal) + } + } + }) +} + +const score = boxes.reduce((prev, box, boxIndex) => + box.reduce((acc, lens, slot) => + (boxIndex + 1) * (slot + 1) * lens.focal + acc + , 0) + prev + , 0) +console.log(score) \ No newline at end of file