-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.ts
74 lines (66 loc) · 1.72 KB
/
15.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { SUM } from "../utils/helpers.js";
import Task, { TaskPartSolution } from "../utils/task.js";
const hash = (s: string): number =>
s.split("").reduce((acc, c) => {
const n = c.charCodeAt(0);
return ((acc + n) * 17) % 256;
}, 0);
const part1: TaskPartSolution = (input) => {
return SUM(input.split(",").map(hash));
};
interface Lens {
label: string;
f: number;
}
const printBoxes = (boxes: Lens[][]) => {
boxes.forEach((b, i) => {
if (b.length > 0) {
console.log(`Box ${i}: ${b.map((l) => `[${l.label} ${l.f}]`).join(" ")}`);
}
});
};
const part2: TaskPartSolution = (input) => {
const boxes: Lens[][] = new Array(256).fill(1).map(() => []);
const steps = input.split(",");
steps.forEach((s) => {
if (s[s.length - 1] === "-") {
const label = s.slice(0, -1);
const h = hash(label);
boxes[h] = boxes[h].filter((l) => l.label !== label);
} else {
const [label, n] = s.split("=");
const h = hash(label);
const l = boxes[h].find((l) => l.label === label);
if (l) {
l.f = Number(n);
} else {
boxes[h].push({ f: Number(n), label });
}
}
// console.log(`After "${s}"`);
// printBoxes(boxes);
// console.log();
});
return SUM(
boxes.map((b, i) => {
return SUM(
b.map((lens, j) => {
const res = (1 + i) * (j + 1) * lens.f;
// console.log(lens, res);
return res;
})
);
})
);
};
const task = new Task(2023, 15, part1, part2, {
part1: {
input: `rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7`,
result: "1320",
},
part2: {
input: `rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7`,
result: "145",
},
});
export default task;