-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
80 lines (68 loc) · 2.17 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace AdventOfCode2016.Day09
{
internal class Solution
{
private readonly string _input;
public Solution(string input)
{
_input = input;
}
public long PartOne()
{
var result = "";
var i = 0;
while (i < _input.Length)
{
if (_input[i] == '(')
{
var j = _input.IndexOf(')', i);
var marker = _input[i..j];
var (count, repeat) = ParseMarker(marker);
var sequence = _input.Substring(j + 1, count);
result += string.Concat(Enumerable.Repeat(sequence, repeat));
i = j + count + 1;
}
else
{
result += _input[i];
i++;
}
}
return result.LongCount();
}
public long PartTwo() => GetLength(_input);
private static long GetLength(string compressed)
{
var length = 0L;
var i = 0;
while (i < compressed.Length)
{
if (compressed[i] == '(')
{
var j = compressed.IndexOf(')', i);
var marker = compressed[i..j];
var (count, repeat) = ParseMarker(marker);
var sequenceLength = GetLength(compressed.Substring(j + 1, count));
length += sequenceLength * repeat;
i = j + count + 1;
}
else
{
i++;
length++;
}
}
return length;
}
private static (int Count, int Repeat) ParseMarker(string marker)
{
var segments = marker.Trim('(', ')').Split('x').Select(int.Parse).ToArray();
return (segments[0], segments[1]);
}
}
}