Skip to content

Commit 0f31993

Browse files
committed
feat: 2024 Day 17 Part 1
1 parent 89cf239 commit 0f31993

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

2024/day/17/part/1/solve.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import solve from "./solve.ts";
2+
3+
import { assertEquals } from "@std/assert";
4+
5+
Deno.test("example", () => {
6+
const input = `\
7+
Register A: 729
8+
Register B: 0
9+
Register C: 0
10+
11+
Program: 0,1,5,4,3,0`;
12+
13+
assertEquals(solve(input), "4,6,3,5,6,3,5,2,1,0");
14+
});

2024/day/17/part/1/solve.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
export default function solve(input: string) {
2+
const [top, bottom] = input.split("\n\n");
3+
const output: number[] = [];
4+
let [a, b, c] = top.matchAll(/\d+/g)!.map(([v]) => +v);
5+
const program = bottom.split(": ")[1].split(",").map(Number);
6+
function combo(operand: number) {
7+
if (operand < 4) return operand;
8+
switch (operand) {
9+
case 0:
10+
case 1:
11+
case 2:
12+
return operand;
13+
case 4:
14+
return a;
15+
case 5:
16+
return b;
17+
case 6:
18+
return c;
19+
default:
20+
throw new Error(`unsupported combo literal: ${operand}`);
21+
}
22+
}
23+
function div(operand: number) {
24+
return Math.trunc(a / 2 ** combo(operand));
25+
}
26+
for (let ip = 0; ip in program;) {
27+
const opcode = program[ip++];
28+
const operand = program[ip++];
29+
switch (opcode) {
30+
case 0: // adv
31+
a = div(operand);
32+
break;
33+
case 1: // bxl
34+
b = b ^ operand;
35+
break;
36+
case 2: // bst
37+
b = combo(operand) % 8;
38+
break;
39+
case 3: // jnz
40+
if (a) ip = operand;
41+
break;
42+
case 4: // bxc
43+
b ^= c;
44+
break;
45+
case 5: // out
46+
output.push(combo(operand) % 8);
47+
break;
48+
case 6: // bdv
49+
b = div(operand);
50+
break;
51+
case 7: // cdv
52+
c = div(operand);
53+
break;
54+
}
55+
}
56+
return output.join(",");
57+
}

0 commit comments

Comments
 (0)