-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day03.cs
84 lines (72 loc) · 2.31 KB
/
Day03.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
using System;
using System.Runtime.CompilerServices;
using AdventOfCode.CSharp.Common;
namespace AdventOfCode.CSharp.Y2016.Solvers;
public class Day03 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
int part1Total = 0;
int part2Total = 0;
int part2SideNum = 0;
Span<int> prevSides = stackalloc int[6];
foreach (ReadOnlySpan<byte> line in input.SplitLines())
{
ParseLine(line, out int side1, out int side2, out int side3);
if (IsValidTriangle(side1, side2, side3))
{
part1Total++;
}
if (part2SideNum == 2)
{
if (IsValidTriangle(prevSides[0], prevSides[3], side1))
{
part2Total++;
}
if (IsValidTriangle(prevSides[1], prevSides[4], side2))
{
part2Total++;
}
if (IsValidTriangle(prevSides[2], prevSides[5], side3))
{
part2Total++;
}
part2SideNum = 0;
}
else
{
prevSides[3 * part2SideNum] = side1;
prevSides[3 * part2SideNum + 1] = side2;
prevSides[3 * part2SideNum + 2] = side3;
part2SideNum++;
}
}
solution.SubmitPart1(part1Total);
solution.SubmitPart2(part2Total);
}
private static void ParseLine(ReadOnlySpan<byte> line, out int side1, out int side2, out int side3)
{
var reader = new SpanReader(line);
reader.SkipWhile(' ');
side1 = reader.ReadPosIntUntil(' ');
reader.SkipWhile(' ');
side2 = reader.ReadPosIntUntil(' ');
reader.SkipWhile(' ');
side3 = reader.ReadPosIntUntilEnd();
}
private static bool IsValidTriangle(int side1, int side2, int side3)
{
// ensure that side3 is the largest side
SwapIfGreater(ref side1, ref side3);
SwapIfGreater(ref side2, ref side3);
return side1 + side2 > side3;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void SwapIfGreater(ref int i, ref int j)
{
if (i > j)
{
(j, i) = (i, j);
}
}
}