-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday8_3.ts
62 lines (54 loc) · 1.29 KB
/
day8_3.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
import { group } from "console";
import { textInput } from "./day8Data";
const testData = `nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6`;
const input = testData;
//let splitted = input.trim().split("\n");
let instructions = input
//.trim()
.split("\n")
.map((instructions) => {
const [opCode, opArgument] = instructions.split(" ");
return {
opCode,
opArgument: 1 * parseInt(opArgument),
executed: false,
};
});
const executors = {
nop(argument, context) {
context.instructionsIndex++;
},
acc(argument, context) {
context.accumulator += argument;
context.instructionsIndex++;
},
jmp(argument, context) {
context.instructionsIndex += argument;
},
};
const execute = (instructions) => {
const context = {
instructions,
instructionsIndex: 0,
accumulator: 0,
};
let instruction = context.instructions[context.instructionsIndex];
while (!instruction.executed) {
if (!(instruction.opCode in executors)) {
throw new Error(`Unknown opcode ${instruction.opCode}`);
}
executors[instruction.opCode](instruction.opArgument, context);
instruction.executed = true;
instruction = context.instructions[context.instructionsIndex];
}
console.log(context.accumulator);
};
execute(instructions);