-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay8.cs
124 lines (101 loc) · 2.94 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using System;
using System.Linq;
namespace aoc2020
{
public class Day8 : AocBase
{
private int pointer;
private int accumulator;
public Day8()
{
Console.WriteLine("Day 8");
var input = LoadInput<string>(@"input\day8.txt").ToArray();
Console.WriteLine("Part 1");
Part1(input);
Console.WriteLine("Part 2");
Part2(input);
}
private void Part1(string[] input)
{
var operations = input.Select(x => new OpCode(x)).ToArray();
Execute(operations);
}
private void Part2(string[] input)
{
for (var i = 0; i < input.Length; i++)
{
var newOpCodes = input.Select(x => new OpCode(x)).ToArray();
var swapped = false;
if (newOpCodes[i].Op == "nop")
{
newOpCodes[i].Op = "jmp";
swapped = true;
}
else if (newOpCodes[i].Op == "jmp")
{
newOpCodes[i].Op = "nop";
swapped = true;
}
if (!swapped)
{
continue;
}
var res = Execute(newOpCodes, false);
if (res)
{
Console.WriteLine($"Accumulator : {accumulator}");
break;
}
}
}
private bool Execute(OpCode[] operations, bool logOnLoop = true)
{
pointer = 0;
accumulator = 0;
while (true)
{
if (pointer >= operations.Length)
{
// finished ok
return true;
}
var curr = operations[pointer];
if (curr.HitCount == 1)
{
// looping
if (logOnLoop)
{
Console.WriteLine($"Accumulator : {accumulator}");
}
return false;
}
curr.HitCount++;
switch (curr.Op)
{
case "nop":
++pointer;
break;
case "acc":
accumulator += curr.Val;
++pointer;
break;
case "jmp":
pointer += curr.Val;
break;
}
}
}
}
public class OpCode
{
public string Op { get; set; }
public int Val { get; set; }
public int HitCount { get; set; } = 0;
public OpCode(string input)
{
var parts = input.Split(' ');
Op = parts[0];
Val = int.Parse(parts[1]);
}
}
}