Skip to content

Commit

Permalink
2018 Day04 solved
Browse files Browse the repository at this point in the history
  • Loading branch information
smabuk committed Nov 10, 2023
1 parent 0939724 commit ac511f2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
39 changes: 30 additions & 9 deletions Solutions/2018/Day04.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@
/// https://adventofcode.com/2018/day/04
/// </summary>
[Description("Repose Record")]
public sealed partial class Day04 {
public sealed partial class Day04
{

[Init]
public static void Init(string[] input, params object[]? _) => LoadShifts(input);
public static void Init(string[] input, params object[]? _) => LoadShifts(input);
public static string Part1(string[] input, params object[]? _) => Solution1(input).ToString();
public static string Part2(string[] input, params object[]? _) => Solution2(input).ToString();

private static readonly List<Asleep> _sleeps = [];

private static void LoadShifts(string[] input) {
private static void LoadShifts(string[] input)
{
List<string> sortedInput = [.. input];
sortedInput.Sort();

Expand All @@ -37,7 +39,8 @@ private static void LoadShifts(string[] input) {
static int GetGuardId(string input) => int.Parse(input[26..].Split(' ')[0]);
}

private static int Solution1(string[] _) {
private static int Solution1(string[] _)
{
int guardId = _sleeps
.GroupBy(x => x.GuardId)
.Select(x => new
Expand All @@ -64,11 +67,29 @@ private static int Solution1(string[] _) {
return guardId * bestMinute;
}

private static string Solution2(string[] input) {
//string inputLine = input[0];
//List<string> inputs = input.ToList();
//List<Guard> instructions = input.Select(ParseLine).ToList();
return "** Solution not written yet **";
private static int Solution2(string[] input)
{
int bestGuardId = 0;
int bestMinute = 0;
int bestCount = 0;
for (int minute = 0; minute < 60; minute++) {
var sleepCount = _sleeps
.GroupBy(x => x.GuardId)
.Select(x => new
{
GuardId = x.Key,
TimesAsleep = x.Count(sleep => sleep.IsAsleep(minute))
})
.OrderByDescending(x => x.TimesAsleep)
.First();
if (sleepCount.TimesAsleep > bestCount) {
bestCount = sleepCount.TimesAsleep;
bestGuardId = sleepCount.GuardId;
bestMinute = minute;
}
}

return bestGuardId * bestMinute;
}

private record Asleep(int GuardId, TimeOnly Start, TimeOnly End)
Expand Down
2 changes: 1 addition & 1 deletion Tests/2018/Tests_04.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public void Part1(string input, int expected)
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
"""
, 000)]
, 4455)]
public void Part2(string input, int expected)
{
_ = int.TryParse(SolutionRouter.SolveProblem(YEAR, DAY, PART2, input), out int actual);
Expand Down

0 comments on commit ac511f2

Please sign in to comment.