Advertisement
R7900

DayNineteen

Mar 31st, 2021
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using static AdventOfCode2020.Common;
  6.  
  7. namespace AdventOfCode2020.Days
  8. {
  9. public class DayNineteen
  10. {
  11. private readonly string[] _input;
  12. private readonly Dictionary<string, string> _data;
  13.  
  14. public DayNineteen()
  15. {
  16. _input = ReadRaw("daynineteen.txt").Split("\n\n");
  17. _data = new Dictionary<string, string>();
  18. _input[0].Split("\n").ToList().ForEach(x => Parse(x));
  19. }
  20.  
  21. public void Process()
  22. {
  23. Console.WriteLine($"Part 1 : {CountMatches()}");
  24.  
  25. _data["8"] = "( 42 | 42 8 )";
  26. _data["11"] = "( 42 31 | 42 11 31 )";
  27.  
  28. Console.WriteLine($"Part 2 : {CountMatches()}");
  29. }
  30.  
  31. private int CountMatches()
  32. {
  33. var regex = $"^{GenerateRegex()}$";
  34. return _input[1].Split("\n").Where(x => Regex.IsMatch(x, regex)).Count();
  35. }
  36.  
  37. private string GenerateRegex()
  38. {
  39. var current = _data["0"].Split(" ").ToList();
  40. while (current.Any(x => x.Any(y => char.IsDigit(y))) && current.Count() < 100000)
  41. {
  42. current = current.Select(x => _data.ContainsKey(x) ? _data[x] : x).SelectMany(x => x.Split(" ")).ToList();
  43. }
  44. current.Remove("8");
  45. current.Remove("11");
  46.  
  47. return string.Join("", current);
  48. }
  49.  
  50. private void Parse(string line)
  51. {
  52. var colonDelimited = line.Split(":");
  53. var key = colonDelimited[0];
  54.  
  55. var value = colonDelimited[1].Replace("\"","").Trim();
  56. if (value.Contains("|"))
  57. {
  58. var delimited = value.Split("|");
  59. value = $"( {delimited[0]} | {delimited[1]} )";
  60. }
  61.  
  62. _data.Add(key, value);
  63. }
  64. }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement