Program.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. namespace D15._1
  7. {
  8. class Program
  9. {
  10. public class R : StreamReader, IEnumerable
  11. {
  12. public R(Stream stream) : base(stream) { }
  13. public IEnumerator GetEnumerator()
  14. {
  15. while (true)
  16. {
  17. var line = ReadLine();
  18. if (line == null) break;
  19. yield return line;
  20. }
  21. }
  22. }
  23. static void Main(string[] args)
  24. {
  25. List<(int positions, int position)> discs = new List<(int, int)>();
  26. var regex = new Regex(@"Disc #\d has (?<n>\d+) positions; at time=0, it is at position (?<t>\d+).");
  27. using (var file = new R(File.OpenText(args[0]).BaseStream))
  28. {
  29. foreach (string line in file)
  30. {
  31. var result = regex.Match(line);
  32. discs.Add((int.Parse(result.Groups["n"].Value), int.Parse(result.Groups["t"].Value)));
  33. }
  34. }
  35. Console.WriteLine($"Part 1 answer is : {RunMachine(discs)}");
  36. discs.Add((11, 0));
  37. Console.WriteLine($"Part 2 answer is : {RunMachine(discs)}");
  38. }
  39. private static int RunMachine(List<(int positions, int position)> discs)
  40. {
  41. for (int startTime = 0; ; ++startTime)
  42. {
  43. int ball = 0;
  44. foreach (var (positions, position) in discs)
  45. {
  46. ball++;
  47. var t = startTime + ball;
  48. if ((position + t) % positions != 0)
  49. {
  50. ball = 0;
  51. break;
  52. }
  53. }
  54. if (ball == discs.Count)
  55. return startTime;
  56. }
  57. }
  58. }
  59. }