-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day2.cs
121 lines (97 loc) · 3.01 KB
/
Day2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
namespace AoC2023;
public class Day2 : IDay<IEnumerable<string>, int>
{
public static int SolvePart1(IEnumerable<string> input)
{
Dictionary<string, int> cubeCounts =
new()
{
{ "red", 12 },
{ "green", 13 },
{ "blue", 14 }
};
var sum = 0;
foreach (var line in input)
{
var gameEliminated = false;
var game = ParseGame(line);
foreach (var cubeResult in game.GetAllCubeResults())
{
var maxCubeCount = cubeCounts[cubeResult.Type];
if (cubeResult.Count > maxCubeCount)
{
gameEliminated = true;
break;
}
}
if (!gameEliminated)
{
sum += game.Id;
}
}
return sum;
}
public static int SolvePart2(IEnumerable<string> input)
{
List<int> gamePowers = [];
foreach (var line in input)
{
var game = ParseGame(line);
var minCubesRequired = new Dictionary<string, int>
{
{ "red", 0 },
{ "blue", 0 },
{ "green", 0 }
};
foreach (var cubeResult in game.GetAllCubeResults())
{
var currentMinCount = minCubesRequired[cubeResult.Type];
if (currentMinCount < cubeResult.Count)
{
minCubesRequired[cubeResult.Type] = cubeResult.Count;
}
}
gamePowers.Add(minCubesRequired.Values.Aggregate(1, (res, el) => res * el));
}
return gamePowers.Sum();
}
private static CubeResult ParseCubeResult(string str)
{
var split = str.Trim().Split(' ');
var count = int.Parse(split[0].Trim());
var type = split[1];
return new CubeResult(count, type);
}
private static Game ParseGame(string str)
{
var lineSplit = str.Split(':');
var gameId = int.Parse(lineSplit[0].Split(' ')[1]);
var sets = lineSplit[1].Split(';');
return new Game(gameId, GetSets(sets));
}
private static Set ParseSet(string str)
{
var cubeResultsStr = str.Split(',');
return new Set(GetCubeResults(cubeResultsStr));
}
private static IEnumerable<CubeResult> GetCubeResults(string[] resultStrs)
{
foreach (var resultStr in resultStrs)
{
yield return ParseCubeResult(resultStr);
}
}
private static IEnumerable<Set> GetSets(string[] setStrs)
{
foreach (var setStr in setStrs)
{
yield return ParseSet(setStr);
}
}
public record CubeResult(int Count, string Type);
public record Set(IEnumerable<CubeResult> Results);
public record Game(int Id, IEnumerable<Set> Sets)
{
public IEnumerable<CubeResult> GetAllCubeResults() => Sets.SelectMany(S => S.Results);
}
}