Program.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4. namespace D06._2
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. if (args.Length < 1) throw new ArgumentException();
  11. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  12. var regex = new Regex(@"(?<verb>turn on|turn off|toggle) (?<x1>\d+),(?<y1>\d+) through (?<x2>\d+),(?<y2>\d+)");
  13. const int size = 1000;
  14. var lights = new int[size, size];
  15. using (var file = File.OpenText(args[0]))
  16. {
  17. while (true)
  18. {
  19. var line = file.ReadLine();
  20. if (line == null) break;
  21. var result = regex.Match(line);
  22. (int x, int y) p1 = (int.Parse(result.Groups["x1"].Value), int.Parse(result.Groups["y1"].Value));
  23. (int x, int y) p2 = (int.Parse(result.Groups["x2"].Value), int.Parse(result.Groups["y2"].Value));
  24. var verb = result.Groups["verb"].Value;
  25. for (int x = p1.x; x <= p2.x; ++x)
  26. for (int y = p1.y; y <= p2.y; ++y)
  27. {
  28. switch (verb)
  29. {
  30. case "turn on": lights[x, y]++; break;
  31. case "turn off": lights[x, y] = Math.Max(lights[x, y] - 1, 0); break;
  32. case "toggle": lights[x, y] = lights[x, y] += 2; break;
  33. }
  34. }
  35. }
  36. }
  37. var answer = 0;
  38. for (int x = 0; x < size; ++x)
  39. for (int y = 0; y < size; ++y)
  40. answer += lights[x, y];
  41. Console.WriteLine($"The answer is : {answer}");
  42. }
  43. }
  44. }