generated from mazharenko/aoc-agent-template-multipleyears
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay07.cs
80 lines (70 loc) · 1.77 KB
/
Day07.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
namespace aoc.Year2024;
internal partial class Day07
{
private readonly Example example = new(
"""
190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20
""");
public Equation[] Parse(string input)
{
return
Numerics.IntegerInt64.ThenIgnore(Span.EqualTo(": "))
.Then(Numerics.IntegerInt64.ManyDelimitedBySpaces())
.Select((res, operands) => new Equation(res, operands))
.Lines().Parse(input);
}
public record Equation(long Result, long[] Operands);
private bool CanBeTrue(Equation equation, Func<long, long, long>[] operators)
{
return CanBeTrue(equation.Result, equation.Operands[0], equation.Operands.AsSpan()[1..], operators);
}
private bool CanBeTrue(long expectedResult, long accResult, ReadOnlySpan<long> operands, Func<long, long, long>[] operators)
{
if (operands.Length == 0)
return expectedResult == accResult;
var head = operands[0];
var rest = operands[1..];
foreach (var op in operators)
if (CanBeTrue(expectedResult, op(accResult, head), rest, operators))
return true;
return false;
}
internal partial class Part1
{
public Part1()
{
}
public long Solve(Equation[] equations)
{
var operators = new Func<long, long, long>[] { (x, y) => x + y, (x, y) => x * y };
return equations
.Where(eq => CanBeTrue(eq, operators)).Sum(equation => equation.Result);
}
}
internal partial class Part2
{
public Part2()
{
Expect(example, 11387);
}
public long Solve(Equation[] equations)
{
var operators = new Func<long, long, long>[]
{
(x, y) => x + y,
(x, y) => x * y,
(x, y) => long.Parse($"{x}{y}")
};
return equations
.Where(eq => CanBeTrue(eq, operators)).Sum(equation => equation.Result);
}
}
}