-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day07.cs
70 lines (60 loc) · 2.19 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
using AdventOfCode.CSharp.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace AdventOfCode.CSharp.Y2015.Solvers;
public class Day07 : ISolver
{
public static void Solve(ReadOnlySpan<byte> input, Solution solution)
{
var rules = new Dictionary<string, string>();
foreach (Range lineRange in input.SplitLines())
{
ReadOnlySpan<byte> line = input[lineRange];
int lastSpaceIndex = line.LastIndexOf((byte)' ');
string variableName = Encoding.ASCII.GetString(line[(lastSpaceIndex + 1)..]);
rules[variableName] = Encoding.ASCII.GetString(line[..(lastSpaceIndex - 3)]);
}
var knownValues = new Dictionary<string, ushort>();
ushort part1 = GetValue("a");
knownValues.Clear();
knownValues["b"] = part1;
ushort part2 = GetValue("a");
solution.SubmitPart1(part1);
solution.SubmitPart2(part2);
ushort GetValue(string variableName)
{
if (ushort.TryParse(variableName, out ushort value))
{
return value;
}
if (knownValues.TryGetValue(variableName, out value))
{
return value;
}
string rule = rules[variableName];
int firstSpaceIndex = rule.IndexOf(' ');
if (firstSpaceIndex == -1)
{
value = GetValue(rule);
}
else if (rule.StartsWith("NOT"))
{
value = (ushort)~GetValue(rule[4..]);
}
else
{
ushort leftVal = GetValue(rule[..firstSpaceIndex]);
value = (ushort)(rule[firstSpaceIndex + 1] switch
{
'A' => leftVal & GetValue(rule[(firstSpaceIndex + 5)..]),
'O' => leftVal | GetValue(rule[(firstSpaceIndex + 4)..]),
'R' => leftVal >> GetValue(rule[(firstSpaceIndex + 8)..]),
'L' => leftVal << GetValue(rule[(firstSpaceIndex + 8)..]),
_ => 0,
});
}
return knownValues[variableName] = value;
}
}
}