1
0

Program.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace D12._2
  5. {
  6. class Rules : Dictionary<string, char> { }
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. if (args.Length < 1) return;
  12. if (File.Exists(args[0]) == false) return;
  13. var file = File.OpenText(args[0]);
  14. var state = file.ReadLine().Substring(@"initial state: ".Length);
  15. file.ReadLine();
  16. var ruleset = new Rules();
  17. do
  18. {
  19. var line = file.ReadLine();
  20. if (line == null) break;
  21. var s = line.Split(" => ");
  22. ruleset.Add(s[0], s[1][0]);
  23. } while (true);
  24. int left = 0;
  25. int last = 0;
  26. int prev = 0;
  27. int cycleresult = 0;
  28. int prevcycleresult = 0;
  29. int gen = 0;
  30. while (true)
  31. {
  32. string nstate = "";
  33. for (int j = -2; j < state.Length + 2; ++j)
  34. nstate += getState(state, j, ruleset);
  35. left -= 2;
  36. state = nstate;
  37. last = CalcResult(state, left);
  38. cycleresult = last - prev;
  39. gen++;
  40. if (cycleresult == prevcycleresult) break;
  41. prevcycleresult = cycleresult;
  42. prev = last;
  43. }
  44. var result = (50000000000 - gen) * cycleresult + last;
  45. Console.WriteLine($"The result is {result}");
  46. }
  47. private static int CalcResult(string state, int l)
  48. {
  49. int left = l;
  50. int result = 0;
  51. foreach (char c in state)
  52. {
  53. if (c == '#') result += left;
  54. left++;
  55. }
  56. return result;
  57. }
  58. static char getState(string state, int p, Rules rules)
  59. {
  60. var sb = "";
  61. for (var i = -2; i <= 2; ++i)
  62. sb += p + i < 0 || p + i >= state.Length ? '.' : state[p + i];
  63. return rules[sb];
  64. }
  65. }
  66. }