-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathDay09.cs
92 lines (81 loc) · 2.09 KB
/
Day09.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
using System;
using System.Runtime.CompilerServices;
using AdventOfCode.CSharp.Common;
namespace AdventOfCode.CSharp.Y2020.Solvers;
public class Day09 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
int lines = input.Count((byte)'\n');
long[] nums = new long[lines];
int line = 0;
var reader = new SpanReader(input);
while (line < 25)
{
nums[line++] = reader.ReadPosLongUntil('\n');
}
while (!reader.Done)
{
long num = reader.ReadPosLongUntil('\n');
nums[line] = num;
if (!IsSumInPrevious25(nums, line, num))
{
break;
}
line++;
}
long part1 = nums[line];
long part2 = SolvePart2(nums, part1);
solution.SubmitPart1(part1);
solution.SubmitPart2(part2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsSumInPrevious25(long[] nums, int line, long num)
{
for (int i = line - 25; i <= line - 2; i++)
{
long target = num - nums[i];
for (int j = i + 1; j <= line - 1; j++)
{
if (nums[j] == target)
{
return true;
}
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static long SolvePart2(long[] nums, long part1)
{
int l = 0;
int r = 0;
long sum = nums[0];
while (sum != part1)
{
if (sum < part1)
{
sum += nums[++r];
}
else
{
sum -= nums[l++];
}
}
long min = nums[l];
long max = nums[l];
for (int i = l + 1; i <= r; i++)
{
long v = nums[i];
if (v < min)
{
min = v;
}
else if (v > max)
{
max = v;
}
}
return min + max;
}
}