-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay07.cs
67 lines (62 loc) · 1.99 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
using System;
using System.Collections.Generic;
using System.Linq;
namespace AdventOfCode2024
{
internal class Day07 : Solution
{
readonly (long target, long[] numbers)[] equations;
public Day07(string input)
: base(input)
{
equations = input
.Split('\n', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(": "))
.Select(x =>
(long.Parse(x[0]), x[1].Split(' ').Select(y => long.Parse(y)).ToArray())
)
.ToArray();
}
public override string Part1()
{
Func<long, long, long>[] operators = [(x, y) => x + y, (x, y) => x * y];
return Solve(operators);
}
public override string Part2()
{
Func<long, long, long>[] operators =
[
(x, y) => x + y,
(x, y) => x * y,
(x, y) => long.Parse(x.ToString() + y.ToString()),
];
return Solve(operators);
}
private string Solve(Func<long, long, long>[] operators)
{
long possiblyTrue = 0;
foreach (var (target, numbers) in equations)
{
List<long> lhs = [numbers[0]];
for (int i = 1; i < numbers.Length; i++)
{
List<long> newLhs = [];
// calculate all (lhs op numbers[i]) combinations
foreach (long l in lhs)
{
foreach (var op in operators)
{
newLhs.Add(op(l, numbers[i]));
}
}
lhs = newLhs;
}
if (lhs.Contains(target))
{
possiblyTrue += target;
}
}
return possiblyTrue.ToString();
}
}
}