advent-of-code-2023/src/day_fifteen.ts

57 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-12-20 11:05:24 +00:00
import fs from "fs";
export const hash = (input: string): number => {
const parts = input.split('');
let hash = 0;
for (let i = 0; i < parts.length; i++) {
hash += parts[i].charCodeAt(0);
hash *= 17;
hash %= 256;
}
return hash;
}
export const hashSum = (input: string): number => {
return input.split(',').reduce((sum, part) => sum + hash(part), 0);
}
const focusingPower = (boxNumber: number, slot: number, value: number): number => {
return (1 + boxNumber) * (1 + slot) * value;
}
export const totalFocusingPower = (input: string): number => {
const boxes: [string, number][][] = new Array(256).fill(0).map(() => []);
input.split(',').forEach(part => {
if (part.includes('=')) {
const [label, value] = part.split('=');
const box = hash(label);
const index = boxes[box].findIndex(([l]) => l === label);
boxes[hash(label)].splice(index === -1 ? boxes[box].length : index, 1, [label, parseInt(value)]);
} else {
const [label] = part.split('-');
let box = hash(label);
const index = boxes[box].findIndex(([l]) => l === label);
if (index !== -1) {
boxes[box].splice(index, 1);
}
}
});
return boxes.reduce(
(sum, box, boxIndex) =>
sum + box.reduce(
(total, [label, value], slot) => {
return total + focusingPower(boxIndex, slot, value)
},
0
),
0
);
}
export const runDayFifteen = () => {
const input = fs.readFileSync('./inputs/day_fifteen_input.txt', 'utf-8').trimEnd();
console.log('Day Fifteen output:', totalFocusingPower(input));
}