-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathDay13.cs
64 lines (51 loc) · 1.56 KB
/
Day13.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
using System;
using System.Collections.Generic;
using System.Numerics;
using AdventOfCode.CSharp.Common;
namespace AdventOfCode.CSharp.Y2020.Solvers;
public class Day13 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
var reader = new SpanReader(input.TrimEnd((byte)'\n'));
int earliestTime = reader.ReadPosIntUntil('\n');
int part1Id = -1;
int part1Time = int.MaxValue;
BigInteger product = 1;
var buses = new List<(int n, int a)>();
for (int i = 0; !reader.Done; i++)
{
if (reader.Peek() == 'x')
{
reader.SkipLength("x,".Length);
continue;
}
int busId = reader.ReadPosIntUntil(',');
// Part 1
int waitTime = busId - (earliestTime % busId);
if (waitTime < part1Time)
{
part1Id = busId;
part1Time = waitTime;
}
// Part 2
product *= busId;
int remainder = (busId - i) % busId;
if (remainder < 0)
{
remainder += busId;
}
buses.Add((busId, remainder));
}
int part1 = part1Id * part1Time;
BigInteger part2 = 0;
foreach ((int n, int a) in buses)
{
BigInteger p = product / n;
part2 += a * BigInteger.ModPow(p, n - 2, n) * p;
}
part2 %= product;
solution.SubmitPart1(part1);
solution.SubmitPart2(part2);
}
}