|
|
|
@ -1,17 +1,19 @@ |
|
|
|
|
using System.Collections; |
|
|
|
|
|
|
|
|
|
namespace aoc2021; |
|
|
|
|
namespace aoc2021; |
|
|
|
|
|
|
|
|
|
/// <summary> |
|
|
|
|
/// Day 10: <see href="https://adventofcode.com/2021/day/10"/> |
|
|
|
|
/// </summary> |
|
|
|
|
public sealed class Day10 : Day |
|
|
|
|
{ |
|
|
|
|
private readonly List<string> _input; |
|
|
|
|
private readonly char[] _openers = { '(', '[', '{', '<' }; |
|
|
|
|
private readonly char[] _closers = { ')', ']', '}', '>' }; |
|
|
|
|
private static readonly Dictionary<char, char> MatchedBrackets = new() |
|
|
|
|
{ |
|
|
|
|
{'(', ')'}, |
|
|
|
|
{'[', ']'}, |
|
|
|
|
{'{', '}'}, |
|
|
|
|
{'<', '>'} |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
private readonly Dictionary<char, int> _scores = new() |
|
|
|
|
private static readonly Dictionary<char, long> Scores = new() |
|
|
|
|
{ |
|
|
|
|
{ ')', 3 }, |
|
|
|
|
{ ']', 57 }, |
|
|
|
@ -19,45 +21,57 @@ public sealed class Day10 : Day |
|
|
|
|
{ '>', 25137 } |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
private readonly Dictionary<char, int> _scoresClosing = new() |
|
|
|
|
private static readonly Dictionary<char, long> ScoresPart2 = new() |
|
|
|
|
{ |
|
|
|
|
{ '(', 1 }, |
|
|
|
|
{ '[', 2 }, |
|
|
|
|
{ '{', 3 }, |
|
|
|
|
{ '<', 4 } |
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
public Day10() : base(10, "Syntax Scoring") |
|
|
|
|
{ |
|
|
|
|
_input = Input.ToList(); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
public override string Part1() |
|
|
|
|
private readonly long _score1; |
|
|
|
|
private readonly List<long> _scores2 = new(); |
|
|
|
|
|
|
|
|
|
public Day10() : base(10, "Syntax Scoring") |
|
|
|
|
{ |
|
|
|
|
var s = new Stack<char>(); |
|
|
|
|
var score = 0; |
|
|
|
|
foreach (var line in _input) |
|
|
|
|
_score1 = 0L; |
|
|
|
|
foreach (var line in Input) |
|
|
|
|
{ |
|
|
|
|
var corrupt = false; |
|
|
|
|
var s = new Stack<char>(); |
|
|
|
|
|
|
|
|
|
foreach (var c in line) |
|
|
|
|
{ |
|
|
|
|
if (_openers.Contains(c)) |
|
|
|
|
if (ScoresPart2.ContainsKey(c)) |
|
|
|
|
{ |
|
|
|
|
s.Push(c); |
|
|
|
|
} |
|
|
|
|
else |
|
|
|
|
{ |
|
|
|
|
var y = s.Pop(); |
|
|
|
|
if (Math.Abs(y - c) <= 3) continue; |
|
|
|
|
score += _scores[c]; |
|
|
|
|
if (c == MatchedBrackets[s.Pop()]) continue; |
|
|
|
|
_score1 += Scores[c]; |
|
|
|
|
corrupt = true; |
|
|
|
|
break; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return score.ToString(); |
|
|
|
|
if (corrupt) continue; |
|
|
|
|
var score2 = 0L; |
|
|
|
|
while (s.Any()) |
|
|
|
|
{ |
|
|
|
|
score2 *= 5; |
|
|
|
|
score2 += ScoresPart2[s.Pop()]; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
_scores2.Add(score2); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
public override string Part1() => $"{_score1}"; |
|
|
|
|
|
|
|
|
|
public override string Part2() |
|
|
|
|
{ |
|
|
|
|
var sorted = _scores2.OrderBy(i => i).ToList(); |
|
|
|
|
return $"{sorted[sorted.Count / 2]}"; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|