-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay13.cs
More file actions
83 lines (67 loc) · 2.28 KB
/
Day13.cs
File metadata and controls
83 lines (67 loc) · 2.28 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using _2024.Utils;
using System.Threading.Tasks;
namespace _2024._13;
public class Day13 : Base
{
public Day13(bool example) : base(example)
{
Day = "13";
}
private static (long, long) GetXAndY(string input)
{
long[] parsed = Regex.Replace(input, @"(Prize: |Button A: |Button B: |X=|Y=|X\+|Y\+)", "")
.Split(", ")
.Select(long.Parse)
.ToArray();
return (parsed[0], parsed[1]);
}
private static long SolvePuzzle(string[] input, int stage)
{
long offset = stage == 1 ? 0 : 10000000000000;
const int tokensA = 3, tokensB = 1;
long cost = 0;
for (int machine = 0; machine < input.Length; machine += 4)
{
// https://math.stackexchange.com/questions/21533/shortcut-for-finding-a-inverse-of-matrix
(long a, long c) = GetXAndY(input[machine]);
(long b, long d) = GetXAndY(input[machine+1]);
(long, long) prize = GetXAndY(input[machine+2]);
long det = a*d - c*b;
if (det == 0)
{
continue;
}
prize = (prize.Item1 + offset, prize.Item2 + offset);
long solA = (long)Math.Round(((double)d * prize.Item1 + (double)-b * prize.Item2)/det);
long solB = (long)Math.Round(((double)-c * prize.Item1 + (double)a * prize.Item2)/det);
if ((solA * a + solB * b) != prize.Item1 || (solA * c + solB * d) != prize.Item2)
{
continue;
}
if (stage == 1 && (solA > 100 || solB > 100))
{
continue;
}
cost += (solA*tokensA) + (solB*tokensB);
}
return cost;
}
public override object PartOne()
{
string[] input = ReadInput();
return SolvePuzzle(input, 1);
}
public override object PartTwo()
{
string[] input = ReadInput();
return SolvePuzzle(input, 2);
}
public override void Reset()
{
}
}