|
|
@@ -0,0 +1,84 @@
|
|
|
+using System;
|
|
|
+using System.Collections.Generic;
|
|
|
+using System.IO;
|
|
|
+
|
|
|
+namespace D23._1
|
|
|
+{
|
|
|
+ public class Machine
|
|
|
+ {
|
|
|
+ public static uint[] Registers { get; set; }
|
|
|
+
|
|
|
+ public Machine() => Registers = new uint[2] { 0, 0 };
|
|
|
+
|
|
|
+ static public int I { get; set; }
|
|
|
+
|
|
|
+ public readonly Dictionary<string, Action<int, int>> OpCodes = new Dictionary<string, Action<int, int>>
|
|
|
+ {
|
|
|
+ { "hlf", (r, o) => Registers[r] /= 2 },
|
|
|
+ { "tpl", (r, o) => Registers[r] *= 3 },
|
|
|
+ { "inc", (r, o) => Registers[r] += 1 },
|
|
|
+ { "jmp", (o, _) => I += o - 1 },
|
|
|
+ { "jie", (r, o) => { if (Registers[r] % 2 == 0) I += o - 1; } },
|
|
|
+ { "jio", (r, o) => { if (Registers[r] == 1) I += o - 1; } },
|
|
|
+ };
|
|
|
+
|
|
|
+ public List<(string, int, int)> Code = new List<(string, int, int)>();
|
|
|
+
|
|
|
+ public void AddLine(string op, int p1, int p2) => Code.Add((op, p1, p2));
|
|
|
+
|
|
|
+ public bool Exec()
|
|
|
+ {
|
|
|
+ (string op, int p1, int p2) = Code[I];
|
|
|
+ OpCodes[op](p1, p2);
|
|
|
+ I++;
|
|
|
+
|
|
|
+ return I < Code.Count;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ class Program
|
|
|
+ {
|
|
|
+ static void Main(string[] args)
|
|
|
+ {
|
|
|
+ if (args.Length < 1) throw new ArgumentException();
|
|
|
+ if (File.Exists(args[0]) == false) throw new FileNotFoundException();
|
|
|
+
|
|
|
+ var pc = ParseFile(args);
|
|
|
+
|
|
|
+ while (pc.Exec()) ;
|
|
|
+
|
|
|
+ Console.WriteLine($"Part 1 answer is {Machine.Registers[1]}");
|
|
|
+
|
|
|
+ Machine.Registers = new uint[] { 1, 0 };
|
|
|
+ Machine.I = 0;
|
|
|
+
|
|
|
+ while (pc.Exec()) ;
|
|
|
+
|
|
|
+ Console.WriteLine($"Part 2 answer is {Machine.Registers[1]}");
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Machine ParseFile(string[] args)
|
|
|
+ {
|
|
|
+ var pc = new Machine();
|
|
|
+ using (var file = File.OpenText(args[0]))
|
|
|
+ {
|
|
|
+ while (true)
|
|
|
+ {
|
|
|
+ var line = file.ReadLine();
|
|
|
+ if (line == null) break;
|
|
|
+
|
|
|
+ var lr = line.Split(" ", 2);
|
|
|
+ var op = lr[0];
|
|
|
+ var vlr = lr[1].Split(", ");
|
|
|
+
|
|
|
+ int p1 = vlr[0] == "a" ? 0 : (vlr[0] == "b" ? 1 : int.Parse(vlr[0]));
|
|
|
+ int p2 = vlr.Length > 1 ? int.Parse(vlr[1]) : 0;
|
|
|
+
|
|
|
+ pc.AddLine(op, p1, p2);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return pc;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|