Skip to content

Commit f3b165f

Browse files
committed
Add day 8 part 2
1 parent 853d0b7 commit f3b165f

File tree

2 files changed

+58
-8
lines changed

2 files changed

+58
-8
lines changed

src/2020/day8/part2.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const runProgram = (program: string[]): number | null => {
2+
let accumulator = 0;
3+
let stackPointer = 0;
4+
5+
while (stackPointer < program.length) {
6+
const instruction = program[stackPointer];
7+
if (instruction === 'EXECUTED') return null; // Loop detected
8+
9+
const [op, arg] = instruction.split(' ');
10+
program[stackPointer] = 'EXECUTED';
11+
12+
if (op === 'acc') {
13+
accumulator += parseInt(arg);
14+
stackPointer++;
15+
} else if (op === 'jmp') {
16+
stackPointer += parseInt(arg);
17+
} else if (op === 'nop') {
18+
stackPointer++;
19+
}
20+
}
21+
22+
return accumulator; // program terminated;
23+
};
24+
25+
export const part2 = (input: string) => {
26+
const instructions = input.split('\n');
27+
28+
for (let i = 0; i < instructions.length - 1; i++) {
29+
const [op, arg] = instructions[i].split(' ');
30+
if (op !== 'acc') {
31+
// Swap jmp and nop and run new program
32+
const newProgram = [...instructions];
33+
newProgram[i] = op === 'jmp' ? `nop ${arg}` : `jmp ${arg}`;
34+
const result = runProgram(newProgram);
35+
if (result) return result;
36+
}
37+
}
38+
};

src/2020/day8/test.spec.ts

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,11 @@
11
import {readInput} from '../../utils';
22

33
import {part1} from './part1';
4+
import {part2} from './part2';
45

56
describe('Advent of Code 2020 - Day 8', () => {
67
let input: string;
7-
beforeAll(async () => {
8-
input = await readInput(__dirname + '/input');
9-
});
10-
11-
describe('part 1', () => {
12-
it('should output 5 of test input ', () => {
13-
const input = `nop +0
8+
const testInput = `nop +0
149
acc +1
1510
jmp +4
1611
acc +3
@@ -19,11 +14,28 @@ acc -99
1914
acc +1
2015
jmp -4
2116
acc +6`;
22-
expect(part1(input)).toBe(5);
17+
18+
beforeAll(async () => {
19+
input = await readInput(__dirname + '/input');
20+
});
21+
22+
describe('part 1', () => {
23+
it('should output 5 of test input ', () => {
24+
expect(part1(testInput)).toBe(5);
2325
});
2426

2527
it('should output 1548 from input', () => {
2628
expect(part1(input)).toBe(1548);
2729
});
2830
});
31+
describe('part 2', () => {
32+
it('should output 8 of test input ', () => {
33+
expect(part2(testInput)).toBe(8);
34+
});
35+
36+
it('should output 1375 from input', () => {
37+
const output = part2(input);
38+
expect(part2(input)).toBe(1375);
39+
});
40+
});
2941
});

0 commit comments

Comments
 (0)