-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathDay02.cs
More file actions
67 lines (56 loc) · 1.84 KB
/
Day02.cs
File metadata and controls
67 lines (56 loc) · 1.84 KB
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
using System;
using AdventOfCode.CSharp.Common;
namespace AdventOfCode.CSharp.Y2023.Solvers;
public class Day02 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
var part1 = 0;
var part2 = 0;
var gameId = 1;
while (input.Length > 1)
{
ParseLine(ref input, gameId, out var maxR, out var maxB, out var maxG);
if (maxR <= 12 && maxG <= 13 && maxB <= 14)
part1 += gameId;
part2 += maxR * maxB * maxG;
gameId++;
}
solution.SubmitPart1(part1);
solution.SubmitPart2(part2);
}
private static ReadOnlySpan<byte> ParseLine(ref ReadOnlySpan<byte> input, int gameId, out int maxR, out int maxB, out int maxG)
{
maxR = 0;
maxB = 0;
maxG = 0;
// skip the "Game 1" part
input = input[("Game ".Length + (gameId < 10 ? 1 : (gameId < 100 ? 2 : 3)))..];
while (input[0] != '\n')
{
// Parse integer
byte c;
var amt = input[2] - '0'; // look at input[2] to skip ": " or ", " or "; "
var i = 3;
while ((c = input[i++]) != ' ')
amt = 10 * amt + (c - '0');
switch (input[i])
{
case (byte)'r':
maxR = Math.Max(maxR, amt);
input = input[(i + "red".Length)..];
break;
case (byte)'g':
maxG = Math.Max(maxG, amt);
input = input[(i + "green".Length)..];
break;
case (byte)'b':
maxB = Math.Max(maxB, amt);
input = input[(i + "blue".Length)..];
break;
}
}
input = input[1..];
return input;
}
}