This commit is contained in:
2023-12-15 11:41:45 +01:00
parent 5c87dcecd2
commit e0206bd8ae
2 changed files with 54 additions and 1 deletions
+1
View File
@@ -16,3 +16,4 @@ 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))
}
console.log(getHash('rn'))
+52
View File
@@ -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)