Program.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D22._1
  6. {
  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. int depth = int.Parse(file.ReadLine().Substring("depth: ".Length));
  15. int[] arrayCoord = file.ReadLine().Substring("target: ".Length).Split(",").Select(s => int.Parse(s)).ToArray();
  16. (int x, int y) coord = (arrayCoord[0], arrayCoord[1]);
  17. file.Close();
  18. Dictionary<(int, int), int> erosionLevels = new Dictionary<(int, int), int>();
  19. int risk = 0;
  20. for (int i = 0; i <= Math.Min(coord.x, coord.y); ++i)
  21. {
  22. for (int y = i; y <= coord.y; ++y)
  23. risk += ComputeRisk(coord, erosionLevels, (i, y), depth);
  24. for (int x = i + 1; x <= coord.x; ++x)
  25. risk += ComputeRisk(coord, erosionLevels, (x, i), depth);
  26. }
  27. Console.WriteLine($"Total risk is : {risk}");
  28. }
  29. private static int ComputeRisk((int x, int y) coord, Dictionary<(int, int), int> erosionLevels, (int x, int y) pos, int depth)
  30. {
  31. int geo = 0;
  32. if (pos != (0, 0) && pos != coord)
  33. {
  34. if (pos.x == 0) geo = pos.y * 48271;
  35. else if (pos.y == 0) geo = pos.x * 16807;
  36. else geo = erosionLevels[(pos.x - 1, pos.y)] * erosionLevels[(pos.x, pos.y - 1)];
  37. }
  38. int ero = (geo + depth) % 20183;
  39. int type = ero % 3;
  40. erosionLevels.Add(pos, ero);
  41. return type;
  42. }
  43. }
  44. }