-
Notifications
You must be signed in to change notification settings - Fork 0
/
2016_09.cs
99 lines (84 loc) · 2.71 KB
/
2016_09.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
using System.Text.RegularExpressions;
namespace AOC.CSharp;
public class AOC2016_09
{
private static Regex MarkerRegex = new Regex(@"\((\d+)x(\d+)\)");
public static long Solve1(string[] lines)
{
return lines.Select(CountDecompressed).Sum();
}
public static long Solve2(string[] lines)
{
return lines.Select(line => Recurse(line, 0, line.Length, 0)).Sum(r => r.Decompressed);
}
private static RecurseResult Recurse(string s, int start, int length, int depth)
{
long decompressed = 0;
int charsProcessed = 0;
int i = start;
while (i < start + length)
{
if (s[i] == '(')
{
string remaining = s.Substring(i);
Match m = MarkerRegex.Match(remaining);
if (m.Success)
{
int repeat = int.Parse(m.Groups[2].Value);
int nextStart = i + m.Groups[0].Length;
int nextLength = int.Parse(m.Groups[1].Value);
RecurseResult recurseResult = Recurse(s, nextStart, nextLength, depth + 1);
decompressed += recurseResult.Decompressed * repeat;
charsProcessed += (recurseResult.CharsProcessed + m.Groups[0].Length);
i += (m.Groups[0].Length + recurseResult.CharsProcessed);
}
else
{
decompressed++;
charsProcessed++;
i++;
}
}
else
{
decompressed++;
charsProcessed++;
i++;
}
}
RecurseResult toReturn = new(decompressed, charsProcessed);
return toReturn;
}
private static int CountDecompressed(string s)
{
int decompressed = 0;
int i = 0;
while (i < s.Length)
{
string remaining = s.Substring(i);
if (remaining[0] == '(')
{
Match m = MarkerRegex.Match(remaining);
if (m.Success)
{
int charCount = int.Parse(m.Groups[1].Value);
int repeat = int.Parse(m.Groups[2].Value);
decompressed += charCount * repeat;
i += (m.Groups[0].Length + charCount);
}
else
{
decompressed++;
i++;
}
}
else
{
decompressed++;
i++;
}
}
return decompressed;
}
private record RecurseResult(long Decompressed, int CharsProcessed);
}