adventofcode/2020/8/Program.cs
2022-12-01 21:02:00 +01:00

87 lines
1.8 KiB
C#

using System;
using System.IO;
using System.Collections.Generic;
namespace day8 {
class Program {
static void Main(string[] args) {
//PartOne();
PartTwo();
}
static void PartOne() {
List<string> lines = new List<string>(File.ReadAllLines("input")) { "hlt" };
int acc = 0, i = 0;
// Halt when reaching HLT
while(lines[i] != "hlt") {
var parts = lines[i].Split(" ");
var instruction = parts[0];
var intval = int.Parse(parts[1]);
// Halt when we go back to this instruction
lines[i] = "hlt";
// Increase accumilator
if(instruction == "acc") acc += intval;
// Do the jump
if(instruction == "jmp") i += intval;
else i++;
}
Console.WriteLine($"The value of the accumilator is {acc}");
}
static void PartTwo() {
var lines = File.ReadAllLines("input");
for(var i=0; i<lines.Length; i++) {
var parts = lines[i].Split(" ");
var instruction = parts[0];
var intval = int.Parse(parts[1]);
if(instruction == "acc")
continue;
var clone = new List<string>(lines);
clone[i] = instruction == "jmp" ? $"nop {intval}" : $"jmp {intval}";
try {
var result = DoTheThing(clone);
Console.WriteLine($"Found that instruction {i} fixes the loop, accumilator end up being {result}.");
return;
} catch { }
}
}
static int DoTheThing(List<string> lines) {
int acc = 0, i = 0;
// Halt when reaching HLT
while(lines[i] != "hlt") {
if(i >= lines.Count) return acc;
var parts = lines[i].Split(" ");
var instruction = parts[0];
var intval = int.Parse(parts[1]);
// Halt when we go back to this instruction
lines[i] = "hlt";
// Increase accumilator
if(instruction == "acc") acc += intval;
// Do the jump
if(instruction == "jmp") i += intval;
else i++;
}
throw new Exception("Lmaoo this isn't it");
}
} // class
} // namespace