-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
111 lines (90 loc) · 3.32 KB
/
Solution.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace AdventOfCode2020.Day18
{
internal class Solution
{
private const string OperatorAdd = "+";
private const string OperatorMultiply = "*";
private static readonly Func<long, long, long> OperationAdd = (lhs, rhs) => lhs + rhs;
private static readonly Func<long, long, long> OperationMultiply = (lhs, rhs) => lhs * rhs;
private readonly IReadOnlyCollection<string> _input;
public Solution(IReadOnlyCollection<string> input)
{
_input = input;
}
public long PartOne()
{
var operators = new Dictionary<string, Operator>
{
[OperatorAdd] = new Operator(1, OperationAdd),
[OperatorMultiply] = new Operator(1, OperationMultiply),
};
var solver = new EquationSolver(operators);
return _input.Sum(solver.Solve);
}
public long PartTwo()
{
var operators = new Dictionary<string, Operator>
{
[OperatorAdd] = new Operator(2, OperationAdd),
[OperatorMultiply] = new Operator(1, OperationMultiply),
};
var solver = new EquationSolver(operators);
return _input.Sum(solver.Solve);
}
}
internal class EquationSolver
{
private const string EquationGroupPattern = @"\([\s\+\*\d]+\)";
private readonly IDictionary<string, Operator> _operators;
public EquationSolver(IDictionary<string, Operator> operators)
{
_operators = operators;
}
public long Solve(string equation)
{
while (Regex.IsMatch(equation, EquationGroupPattern))
{
equation = Regex.Replace(equation, EquationGroupPattern, match =>
{
var group = match.Value.TrimStart('(').TrimEnd(')');
return SolveGroup(group).ToString();
});
}
return SolveGroup(equation);
}
private long SolveGroup(string group)
{
var queue = new Queue<string>(group.Split(" "));
var lhs = long.Parse(queue.Dequeue());
return SolveGroup(queue, lhs, 0);
}
private long SolveGroup(Queue<string> tokens, long lhs, int minPrecedence)
{
while (tokens.TryPeek(out var nextOperator) && _operators[nextOperator].Precedence >= minPrecedence)
{
var @operator = _operators[tokens.Dequeue()];
var rhs = long.Parse(tokens.Dequeue());
while (tokens.TryPeek(out nextOperator) && _operators[nextOperator].Precedence > @operator.Precedence)
{
rhs = SolveGroup(tokens, rhs, _operators[nextOperator].Precedence);
}
lhs = @operator.Operation.Invoke(lhs, rhs);
}
return lhs;
}
}
internal class Operator
{
public Operator(int precedence, Func<long, long, long> operation)
{
Precedence = precedence;
Operation = operation;
}
public int Precedence { get; }
public Func<long, long, long> Operation { get; }
}
}