示例#1
0
文件: Day4.cs 项目: RPScylla/AoC
        public AnswerModel Solve()
        {
            AnswerModel answer = new AnswerModel();

            List <LogEntry>         logEntries = new List <LogEntry>();
            Dictionary <int, Guard> guards     = new Dictionary <int, Guard>();

            foreach (string line in _input)
            {
                // Create a log entry out of every line.
                Match    match = _regex.Match(line);
                LogEntry entry = new LogEntry(match);
                logEntries.Add(entry);

                // If the logentries contains a guard that is not found earlyer add the guard.
                if (entry.GuardId != 0 && !guards.ContainsKey(entry.GuardId))
                {
                    guards.Add(entry.GuardId, new Guard(entry.GuardId));
                }
            }

            // Sort the logentries based on there timestamp.
            logEntries.Sort((x, y) => x.TimeStamp.CompareTo(y.TimeStamp));


            Guard currentGuard = null;
            // keep track of last time asleep.
            LogEntry lastAsleep = new LogEntry();

            // Itterate over logentries.
            foreach (LogEntry logEntry in logEntries)
            {
                switch (logEntry.Event)
                {
                case LogEvent.StartShift:
                    currentGuard = guards[logEntry.GuardId];
                    break;

                case LogEvent.FallAsleep:
                    lastAsleep = logEntry;
                    break;

                case LogEvent.WakeUp:
                    currentGuard.AddSleep(lastAsleep, logEntry);
                    break;
                }
            }

            Guard mostSleep = guards.OrderByDescending(guard => guard.Value.TotalAsleep).First().Value;

            answer.PartA = (mostSleep.Id * mostSleep.HighestMinute);

            Guard highFrequency = guards.OrderByDescending(guard => guard.Value.HighestFrequency).First().Value;

            answer.PartB = (highFrequency.Id * highFrequency.HighestMinute);

            return(answer);
        }