Program.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. namespace D4._2
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. if (args.Length < 1) return;
  13. if (File.Exists(args[0]) == false) return;
  14. var dic = new Dictionary<DateTime, string>();
  15. var guard = new Dictionary<string, Dictionary<int, int>>();
  16. var file = File.OpenText(args[0]);
  17. var regex = new Regex(@"\[(.*)\]");
  18. do
  19. {
  20. var line = file.ReadLine();
  21. if (line == null) break;
  22. var dateStr = line.Substring(0, 18).Trim('[', ']');
  23. var date = DateTime.Parse(dateStr);
  24. dic.Add(date, line.Substring(19, line.Length - 19));
  25. } while (true);
  26. var ordered = dic.OrderBy(kvp => kvp.Key);
  27. string curGuard = string.Empty;
  28. DateTime asleep = DateTime.Now;
  29. foreach (var kvp in ordered)
  30. {
  31. var date = kvp.Key;
  32. var str = kvp.Value;
  33. if (str.StartsWith("Guard")) curGuard = str.Split(' ')[1];
  34. {
  35. if (guard.ContainsKey(curGuard) == false)
  36. {
  37. var d = new Dictionary<int, int>();
  38. for (var i = 0; i < 60; i++) d.Add(i, 0);
  39. guard.Add(curGuard, d);
  40. }
  41. }
  42. if (str == "falls asleep")
  43. {
  44. asleep = date;
  45. }
  46. if (str == "wakes up")
  47. {
  48. for (int m = asleep.Minute; m < date.Minute; m++)
  49. guard[curGuard][m] += 1;
  50. }
  51. }
  52. KeyValuePair<int, int> highestMinute = new KeyValuePair<int, int>(0, 0);
  53. string sleeper = "";
  54. foreach (var g in guard)
  55. {
  56. var minute = g.Value.OrderByDescending(v => v.Value).FirstOrDefault();
  57. if (minute.Value > highestMinute.Value)
  58. {
  59. highestMinute = minute;
  60. sleeper = g.Key;
  61. }
  62. }
  63. Console.WriteLine($"Guard {sleeper} sleeps {highestMinute.Value} times on {highestMinute.Key}th minute");
  64. var id = int.Parse(sleeper.TrimStart('#'));
  65. Console.WriteLine($"Answer : {id * highestMinute.Key}");
  66. }
  67. }
  68. }