Skip to content

Commit 304e862

Browse files
committed
[ts] 2024:01: Solve day01
1 parent e103123 commit 304e862

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

2024/day01/day01.ts

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// @ts-ignore - tl_ls is missing @types/node
2+
import { EOL } from "node:os";
3+
// @ts-ignore - tl_ls doesn't know about Bun
4+
const inputLines = (await Bun.file("input").text()).trim().split(EOL);
5+
6+
let left: Array<number> = [];
7+
let right: Array<number> = [];
8+
9+
class DMap<K> extends Map<K, number> {
10+
getOrDefault(inx: K, fallback: number) { return this.get(inx) ?? fallback; }
11+
getOrZero(inx: K) { return this.getOrDefault(inx, 0); }
12+
increment(inx: K) { this.set(inx, this.getOrZero(inx) + 1); }
13+
}
14+
15+
inputLines
16+
.map((line: string) => line.trim())
17+
.forEach((line: string) => {
18+
const match = line.match(/(\d+)\s+(\d+)/)!;
19+
left.push(parseInt(match[1]));
20+
right.push(parseInt(match[2]));
21+
});
22+
left = left.sort();
23+
right = right.sort();
24+
25+
let solution1 = 0;
26+
let solution2 = 0;
27+
28+
const rightOccurences: DMap<number> = new DMap();
29+
for (const inx in left) {
30+
const lnum = left[inx];
31+
const rnum = right[inx];
32+
33+
solution1 += Math.abs(lnum - rnum);
34+
rightOccurences.increment(rnum);
35+
}
36+
37+
solution2 = left.reduce((acc, lnum) => acc + (lnum * rightOccurences.getOrZero(lnum)), 0);
38+
39+
console.log(`Part 1: ${solution1}${EOL}Part 2: ${solution2}`);

0 commit comments

Comments
 (0)