day 19
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Ben Harris 2021-01-02 12:50:18 -05:00
parent 8571af616b
commit 65dbfd62f0
2 changed files with 38 additions and 9 deletions

View File

@ -26,7 +26,7 @@ namespace aoc2020.test
[DataRow(typeof(Day16), "19093", "5311123569883")]
// [DataRow(typeof(Day17), "293", "1816")]
[DataRow(typeof(Day18), "12918250417632", "171259538712010")]
[DataRow(typeof(Day19), "", "")]
[DataRow(typeof(Day19), "160", "357")]
[DataRow(typeof(Day20), "", "")]
[DataRow(typeof(Day21), "", "")]
[DataRow(typeof(Day22), "", "")]

View File

@ -1,4 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace aoc2020
{
@ -7,24 +10,50 @@ namespace aoc2020
/// </summary>
public sealed class Day19 : Day
{
private readonly string[] _messages;
private readonly Dictionary<string, string[][]> _rules;
private readonly Stack<string> _stack;
public Day19() : base(19, "Monster Messages")
{
_rules = Input.TakeWhile(l => !string.IsNullOrWhiteSpace(l))
.Select(l => l.Split(':'))
.Select(a => (key: a[0],
val: a[1].Split('|', StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToArray()))
.ToDictionary(a => a.key, a => a.val);
_messages = Input.Skip(_rules.Count + 1).ToArray();
_stack = new Stack<string>();
}
private string MakeRegexExpression(string key)
{
if (_stack.Count(s => s == key) > 10) return "x";
_stack.Push(key);
var sub = string.Join("|", _rules[key].Select(test => test.Length switch
{
1 => test[0][0] == '"' ? test[0].Trim('"') : MakeRegexExpression(test[0]),
_ => $"{string.Join(string.Empty, test.Select(MakeRegexExpression))}"
}));
_stack.Pop();
return _rules[key].Length > 1 ? $"({sub})" : sub;
}
public override string Part1()
{
return "";
var exp = new Regex($"^{MakeRegexExpression("0")}$");
var results = _messages.ToLookup(r => exp.IsMatch(r), r => r);
return $"{results[true].Count()}";
}
public override string Part2()
{
return "";
}
private class Rule
{
public int idx { get; init; }
public List<Rule> others { get; set; }
// fix rules 8 and 11
_rules["8"] = new[] {new[] {"42"}, new[] {"42", "8"}};
_rules["11"] = new[] {new[] {"42", "31"}, new[] {"42", "11", "31"}};
var exp = new Regex($"^{MakeRegexExpression("0")}$");
var results = _messages.ToLookup(r => exp.IsMatch(r), r => r);
return $"{results[true].Count()}";
}
}
}