Advertisement
R7900

DayTwentyone

Mar 31st, 2021
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using static AdventOfCode2020.Common;
  6.  
  7. namespace AdventOfCode2020.Days
  8. {
  9. public class DayTwentyone
  10. {
  11. private readonly List<(string[] Allergens, List<string> Ingredients)> _allergens;
  12. private Dictionary<string, List<string>> _foodsWithAllergens;
  13.  
  14. public DayTwentyone()
  15. {
  16. _allergens = new List<(string[], List<string>)>();
  17. _foodsWithAllergens = new Dictionary<string, List<string>>();
  18. var input = ReadFile("daytwentyone.txt").ToList();
  19.  
  20. _allergens = input.Select(x =>
  21. (Allergens: x.Replace(")","").Split(" (contains ")[1].Replace(" ", "").Split(","),
  22. Ingredients: x.Split("(contains")[0].Trim().Split(" ").ToList())).ToList();
  23. }
  24.  
  25. public void Process()
  26. {
  27. Console.WriteLine($"Part 1: {PartOne()}");
  28. Console.WriteLine($"Part 2: {PartTwo()}");
  29. }
  30.  
  31. public int PartOne()
  32. {
  33. var allAllergens = _allergens.SelectMany(x => x.Allergens).Distinct();
  34. foreach (var allergen in allAllergens)
  35. {
  36. var matchingAllergens = _allergens.Where(x => x.Allergens.Contains(allergen)).Select(x => x.Ingredients).ToList();
  37. _foodsWithAllergens.Add(allergen, matchingAllergens.Aggregate((x, y) => x.Intersect(y).ToList()));
  38. }
  39.  
  40. return _allergens.SelectMany(x => x.Ingredients).Where(x => !_foodsWithAllergens.SelectMany(x => x.Value).Distinct().Contains(x)).Count();
  41. }
  42.  
  43. public string PartTwo()
  44. {
  45. while (_foodsWithAllergens.Values.Any(x => x.Count() != 1))
  46. {
  47. var singles = _foodsWithAllergens.Where(x => x.Value.Count() == 1).SelectMany(x => x.Value).ToList();
  48. var nonSingleKeys = _foodsWithAllergens.Where(x => x.Value.Count() > 1).Select(x => x.Key).ToList();
  49. nonSingleKeys.ForEach(x => _foodsWithAllergens[x] = _foodsWithAllergens[x].Where(x => !singles.Contains(x)).ToList());
  50. }
  51.  
  52. return string.Join(",", _foodsWithAllergens.OrderBy(x => x.Key).SelectMany(x => x.Value));
  53. }
  54. }
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement