-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
99 lines (87 loc) · 2.11 KB
/
Program.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 AdventOfCode._2021_10;
using AdventOfCode.Common;
var lines = Resources.GetInputFileLines();
Dictionary<char, char> pairs = new()
{
{ '(', ')' },
{ '[', ']' },
{ '{', '}' },
{ '<', '>' },
};
IEnumerable<char> CompleteLine(string line)
{
var stack = new Stack<char>();
foreach (var current in line)
{
if (pairs.ContainsKey(current))
{
// current is opening bracket
stack.Push(current);
}
else
{
// current is closing bracket
if (stack.TryPop(out var opening))
{
if (!pairs.TryGetValue(opening, out var value) || current != value)
{
// Wrong bracket => corrupted line
throw new CorruptedLineException(current);
}
}
else
{
// Nothing to pop => corrupted line
throw new CorruptedLineException(current);
}
}
}
return stack.Select(c => pairs[c]);
}
static int ScoreCorruption(char c)
{
return c switch
{
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
_ => throw new InvalidOperationException("???"),
};
}
static long ScoreCompletion(IEnumerable<char> missing)
{
if (!missing.Any())
{
return 0;
}
return missing
.Select(c => c switch
{
')' => 1L,
']' => 2L,
'}' => 3L,
'>' => 4L,
_ => throw new InvalidOperationException("???"),
})
.Aggregate((acc, score) => acc * 5 + score);
}
long corruptionScore = 0;
List<long> completionScores = [];
foreach (var line in lines)
{
try
{
completionScores.Add(ScoreCompletion(CompleteLine(line)));
}
catch (CorruptedLineException e)
{
corruptionScore += ScoreCorruption(e.CorruptedChar);
}
}
var scores = completionScores
.Where(s => s > 0)
.OrderBy(s => s)
.ToArray();
Console.WriteLine($"Part 1: {corruptionScore}");
Console.WriteLine($"Part 2: {scores[scores.Length / 2]}");