-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-10-p1.ts
70 lines (65 loc) · 1.6 KB
/
day-10-p1.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
const data = await Deno.readTextFile("./day-10-input.txt");
type Instruction =
| {
kind: "noop";
}
| {
kind: "addx";
val: number;
pendingCycles: number;
};
const instructions: Instruction[] = data.split("\n").map((instStr) => {
if (instStr === "noop") {
return { kind: "noop" };
}
return {
kind: "addx",
val: parseInt(instStr.split(" ")[1], 10),
pendingCycles: 2,
};
});
class CPU {
private registerX = 1;
private instructions: Instruction[];
private cycle = 0;
constructor(instructions: Instruction[]) {
this.instructions = instructions;
}
tick() {
const currentInstruction = this.instructions[0];
if (currentInstruction.kind === "noop") {
this.cycle += 1;
instructions.shift();
} else if (currentInstruction.kind === "addx") {
this.cycle += 1;
currentInstruction.pendingCycles -= 1;
if (currentInstruction.pendingCycles === 0) {
this.registerX += currentInstruction.val;
instructions.shift();
}
}
}
hasInstructionsToExecute() {
return !!this.instructions.length;
}
getCycle() {
return this.cycle;
}
getRegisterX() {
return this.registerX;
}
}
// inspect **during** the cycle, so still use old values!
function simulate() {
const cyclesToInspect = [20, 60, 100, 140, 180, 220];
const cpu = new CPU(instructions);
let result = 0;
while (cpu.hasInstructionsToExecute()) {
if (cyclesToInspect.includes(cpu.getCycle() + 1)) {
result += (cpu.getCycle() + 1) * cpu.getRegisterX();
}
cpu.tick();
}
return result;
}
console.log(simulate());