-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day8.cs
88 lines (77 loc) · 1.87 KB
/
Day8.cs
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
using System;
using System.IO;
class Day8 {
enum OpCode {
nop,
acc,
jmp
}
public static int Solution1() {
LoadProgram(out OpCode[] opCodes, out int[] opValues);
return -Run(0, 0, opCodes, opValues, new bool[opCodes.Length], -1);
}
public static int Solution2() {
int acc = 0;
int ptr = 0;
LoadProgram(out OpCode[] opCodes, out int[] opValues);
bool[] visited = new bool[opCodes.Length];
while (true) {
if (opCodes[ptr] == OpCode.nop || opCodes[ptr] == OpCode.jmp) {
int result = Run(acc, ptr, opCodes, opValues, (bool[])visited.Clone(), ptr);
if (result >= 0) {
return result;
}
}
visited[ptr] = true;
switch (opCodes[ptr]) {
case OpCode.nop:
ptr++;
break;
case OpCode.acc:
acc += opValues[ptr];
ptr++;
break;
case OpCode.jmp:
ptr += opValues[ptr];
break;
}
}
}
static void LoadProgram(out OpCode[] opCodes, out int[] opValues) {
string[] input = File.ReadAllLines("input8.txt");
opCodes = new OpCode[input.Length];
opValues = new int[input.Length];
for (int i = 0; i < input.Length; i++) {
string[] command = input[i].Split(' ');
Enum.TryParse(command[0], out opCodes[i]);
opValues[i] = int.Parse(command[1]);
}
}
static int Run(int acc, int ptr, OpCode[] opCodes, int[] opValues, bool[] visited, int opSwap) {
if (opSwap >= 0) {
opCodes[opSwap] = 2 - opCodes[opSwap];
}
while (ptr < opCodes.Length) {
if (visited[ptr]) {
if (opSwap >= 0) {
opCodes[opSwap] = 2 - opCodes[opSwap];
}
return -acc;
}
visited[ptr] = true;
switch (opCodes[ptr]) {
case OpCode.nop:
ptr++;
break;
case OpCode.acc:
acc += opValues[ptr];
ptr++;
break;
case OpCode.jmp:
ptr += opValues[ptr];
break;
}
}
return acc;
}
}