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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
import { of } from "rxjs";
import { concatAll, map, reduce, toArray } from 'rxjs/operators';
import { ExerciseModuleFunc } from "../types";
const CODES = ["nop", "acc", "jmp"] as const;
interface Instruction {
code: typeof CODES[number];
value: number;
}
const parseToInstruction = (line: string): Instruction => {
const [codeStr, valStr] = line.split(" ");
const value = Number(valStr);
const code = codeStr as Instruction["code"];
return {
code,
value
}
};
interface GraphNode {
value: number;
next: GraphNode | null;
visited: boolean;
}
const indexToNode: { [index: number]: GraphNode } = {};
const toGraph = (instructions: Instruction[], index: number = 0): GraphNode => {
const inst = instructions[index];
if (!inst) return null;
let nextIndex: number;
let value: number;
if (inst.code === "nop") {
value = 0;
nextIndex = index + 1;
} else if (inst.code === "acc") {
value = inst.value;
nextIndex = index + 1;
} else if (inst.code === "jmp") {
value = 0;
nextIndex = index + inst.value;
}
const node = {
value,
next: null,
visited: false
};
indexToNode[index] = node;
const next = indexToNode[nextIndex] || toGraph(instructions, nextIndex);
node.next = next;
return node;
}
const traverseUntilLoop = (graph: GraphNode): GraphNode["value"] => {
let accum = 0;
let current = graph;
while (true) {
current.visited = true;
accum += current.value;
const next = current.next;
if (next.visited) {
break;
} else {
current = next;
}
}
return accum;
}
const day8: ExerciseModuleFunc = async (input: string) => {
const lines = input.split("\n");
const prom1 = of(lines).pipe(
concatAll(),
map(parseToInstruction),
toArray(),
map(toGraph),
map(traverseUntilLoop)
).toPromise();
return Promise.all([prom1]);
}
export default day8;
|