|
| 1 | +type Instruction = { |
| 2 | + op: "nop" | "acc" | "jmp"; |
| 3 | + arg: number; |
| 4 | +}; |
| 5 | + |
| 6 | +const input = (await Deno.readTextFile("/dev/stdin")) |
| 7 | + .split("\n") |
| 8 | + .slice(0, -1); |
| 9 | + |
| 10 | +const instructions = input |
| 11 | + .map((line) => line.split(" ")) |
| 12 | + .map(([op, arg]) => ({ op, arg: parseInt(arg) })) as Instruction[]; |
| 13 | + |
| 14 | +/** --- Part 1 --- */ |
| 15 | +{ |
| 16 | + let ipTracker = new Set<number>([]); |
| 17 | + let accumulator = 0; |
| 18 | + let instructionPointer = 0; |
| 19 | + |
| 20 | + while (!ipTracker.has(instructionPointer)) { |
| 21 | + ipTracker.add(instructionPointer); |
| 22 | + |
| 23 | + const { op, arg } = instructions[instructionPointer]; |
| 24 | + |
| 25 | + switch (op) { |
| 26 | + case "nop": |
| 27 | + instructionPointer += 1; |
| 28 | + break; |
| 29 | + case "acc": |
| 30 | + instructionPointer += 1; |
| 31 | + accumulator += arg; |
| 32 | + break; |
| 33 | + case "jmp": |
| 34 | + instructionPointer += arg; |
| 35 | + break; |
| 36 | + } |
| 37 | + } |
| 38 | + console.log(`${accumulator}`); |
| 39 | +} |
| 40 | + |
| 41 | +/** --- Part 2 --- */ |
| 42 | +{ |
| 43 | + let ipTracker = new Set<number>([]); |
| 44 | + let accumulator = 0; |
| 45 | + let instructionPointer = 0; |
| 46 | + let modIndex = 0; |
| 47 | + |
| 48 | + for ( |
| 49 | + let modStep = instructions.findIndex(({ op }) => |
| 50 | + op === "nop" || op === "jmp" |
| 51 | + ); |
| 52 | + modStep !== -1 && instructionPointer < instructions.length; |
| 53 | + modStep = instructions.slice(modIndex + 1).findIndex(({ op }) => |
| 54 | + op === "nop" || op === "jmp" |
| 55 | + ), modIndex += 1 + modStep |
| 56 | + ) { |
| 57 | + ipTracker = new Set<number>([]); |
| 58 | + accumulator = 0; |
| 59 | + instructionPointer = 0; |
| 60 | + |
| 61 | + const { op: modOp, arg: modArg } = instructions[modIndex]; |
| 62 | + |
| 63 | + const modifiedInstructions = [ |
| 64 | + ...instructions.slice(0, modIndex), |
| 65 | + { arg: modArg, op: modOp === "nop" ? "jmp" : "nop" }, |
| 66 | + ...instructions.slice(modIndex + 1), |
| 67 | + ]; |
| 68 | + |
| 69 | + while ( |
| 70 | + !ipTracker.has(instructionPointer) && |
| 71 | + instructionPointer < instructions.length |
| 72 | + ) { |
| 73 | + ipTracker.add(instructionPointer); |
| 74 | + |
| 75 | + const { op, arg } = modifiedInstructions[instructionPointer]; |
| 76 | + |
| 77 | + switch (op) { |
| 78 | + case "nop": |
| 79 | + instructionPointer += 1; |
| 80 | + break; |
| 81 | + case "acc": |
| 82 | + instructionPointer += 1; |
| 83 | + accumulator += arg; |
| 84 | + break; |
| 85 | + case "jmp": |
| 86 | + instructionPointer += arg; |
| 87 | + break; |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + console.log(`${accumulator}`); |
| 93 | +} |
0 commit comments