Program.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace D23._1
  5. {
  6. public class Machine
  7. {
  8. public static uint[] Registers { get; set; }
  9. public Machine() => Registers = new uint[2] { 0, 0 };
  10. static public int I { get; set; }
  11. public readonly Dictionary<string, Action<int, int>> OpCodes = new Dictionary<string, Action<int, int>>
  12. {
  13. { "hlf", (r, o) => Registers[r] /= 2 },
  14. { "tpl", (r, o) => Registers[r] *= 3 },
  15. { "inc", (r, o) => Registers[r] += 1 },
  16. { "jmp", (o, _) => I += o - 1 },
  17. { "jie", (r, o) => { if (Registers[r] % 2 == 0) I += o - 1; } },
  18. { "jio", (r, o) => { if (Registers[r] == 1) I += o - 1; } },
  19. };
  20. public List<(string, int, int)> Code = new List<(string, int, int)>();
  21. public void AddLine(string op, int p1, int p2) => Code.Add((op, p1, p2));
  22. public bool Exec()
  23. {
  24. (string op, int p1, int p2) = Code[I];
  25. OpCodes[op](p1, p2);
  26. I++;
  27. return I < Code.Count;
  28. }
  29. }
  30. class Program
  31. {
  32. static void Main(string[] args)
  33. {
  34. if (args.Length < 1) throw new ArgumentException();
  35. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  36. var pc = ParseFile(args);
  37. while (pc.Exec()) ;
  38. Console.WriteLine($"Part 1 answer is {Machine.Registers[1]}");
  39. Machine.Registers = new uint[] { 1, 0 };
  40. Machine.I = 0;
  41. while (pc.Exec()) ;
  42. Console.WriteLine($"Part 2 answer is {Machine.Registers[1]}");
  43. }
  44. private static Machine ParseFile(string[] args)
  45. {
  46. var pc = new Machine();
  47. using (var file = File.OpenText(args[0]))
  48. {
  49. while (true)
  50. {
  51. var line = file.ReadLine();
  52. if (line == null) break;
  53. var lr = line.Split(" ", 2);
  54. var op = lr[0];
  55. var vlr = lr[1].Split(", ");
  56. int p1 = vlr[0] == "a" ? 0 : (vlr[0] == "b" ? 1 : int.Parse(vlr[0]));
  57. int p2 = vlr.Length > 1 ? int.Parse(vlr[1]) : 0;
  58. pc.AddLine(op, p1, p2);
  59. }
  60. }
  61. return pc;
  62. }
  63. }
  64. }