private static (IDictionary <string, Rule>, List <string>) Parse(List <string> lines) { var rules = new Dictionary <string, Rule>(); var messages = new List <string>(); foreach (var line in lines) { if (OrRule.MatchesRuleDescription(line)) { var rule = OrRule.Parse(line); rules.Add(rule.Id, rule); } else if (MatchRule.MatchesRuleDescription(line)) { MatchRule matchRule = MatchRule.Parse(line); rules.Add(matchRule.Id, matchRule); } else if (SequenceRule.MatchesRuleDescription(line)) { SequenceRule sequenceRule = SequenceRule.Parse(line); rules.Add(sequenceRule.Id, sequenceRule); } else if (!string.IsNullOrEmpty(line)) { messages.Add(line); } } return(rules, messages); }
public Tuple <Dictionary <int, Rule>, string[]> ParseInput() { var lines = Input.Split("\n", StringSplitOptions.TrimEntries); var i = 0; var rules = new Dictionary <int, Rule>(); while (!string.IsNullOrEmpty(lines[i])) { var a = lines[i].Split(':', StringSplitOptions.TrimEntries); int r = int.Parse(a[0]); if (a[1].Contains('\"')) { rules[r] = BasicRule.Parse(a[1]); } else if (a[1].Contains('|')) { rules[r] = OrRule.Parse(a[1]); } else { rules[r] = MultiRule.Parse(a[1]); } i++; } return(Tuple.Create(rules, lines.Skip(i + 1).ToArray())); }
private static int MatchesRule0Cyclic(List <string> lines) { var(newRules, messages) = Parse(lines); newRules["8"] = OrRule.Parse("8: 42 | 42 8"); newRules["11"] = OrRule.Parse("11: 42 31 | 42 11 31"); var result = messages.Count(message => newRules["0"].IsValid(message, newRules)); return(result); }
protected override string SolvePartTwo() { var parse = ParseInput(); rules = parse.Item1; rules[8] = OrRule.Parse("42 | 42 8"); rules[11] = OrRule.Parse("42 31 | 42 11 31"); var lines = parse.Item2; return(lines.Select(x => Tuple.Create(x, rules[0].Match(x))).Where(x => x.Item2.Length > 0 && x.Item2.Any(y => y == x.Item1.Length - 1)).Count().ToString()); }