Program.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D23._1
  6. {
  7. public class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. int[] Registers = new int[5] {7, 0, 0, 0, 0 };
  12. Work(args, Registers);
  13. Console.WriteLine($"The answer is : {Registers[0]}");
  14. }
  15. public static void Work(string[] args, int[] Registers)
  16. {
  17. List<string[]> instr = File.ReadAllText(args[0]).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)
  18. .Select(n => n.Split(" ")).ToList();
  19. var Ops = new Dictionary<string, Action<bool, bool, int, int>>()
  20. {
  21. { "cpy", (ia, ib, a, b) => {
  22. if (ib == false) return;
  23. Registers[b] = ia ? Registers[a] : a; }
  24. },
  25. { "inc", (ia, ib, a, b) => {
  26. if (ia == false) return;
  27. Registers[a]++; }
  28. },
  29. { "dec", (ia, ib, a, b) => {
  30. if (ia == false) return;
  31. Registers[a]--;
  32. } },
  33. { "jnz", (ia, ib, a, b) => { Registers[4] += (ia ? Registers[a] : a) != 0 ? (ib ? Registers[b] : b) - 1 : 0; } },
  34. { "tgl", (ia, ib, a, b) => {
  35. var ii = (ia ? Registers[a] : a) + Registers[4];
  36. if (ii >= instr.Count) return;
  37. var ins = instr[ii];
  38. if (ins.Length == 2)
  39. ins[0] = ins[0] == "inc" ? "dec" : "inc";
  40. else
  41. ins[0] = ins[0] == "jnz" ? "cpy" : "jnz";
  42. instr[ii] = ins;
  43. } }
  44. };
  45. for (; Registers[4] < instr.Count; Registers[4]++)
  46. {
  47. var i = instr[Registers[4]];
  48. ParseLine(i, out int valuea, out int valueb, out bool isrega, out bool isregb);
  49. Ops[i[0]](isrega, isregb, valuea, valueb);
  50. }
  51. }
  52. private static void ParseLine(string[] i, out int valuea, out int valueb, out bool isrega, out bool isregb)
  53. {
  54. valuea = 0;
  55. valueb = 0;
  56. isrega = false;
  57. isregb = false;
  58. if (i[1][0] >= 'a')
  59. {
  60. valuea = i[1][0] - 'a';
  61. isrega = true;
  62. }
  63. else valuea = int.Parse(i[1]);
  64. if (i.Length == 3)
  65. {
  66. if (i[2][0] >= 'a')
  67. {
  68. valueb = i[2][0] - 'a';
  69. isregb = true;
  70. }
  71. else valueb = int.Parse(i[2]);
  72. }
  73. }
  74. }
  75. }