generated from sindrekjr/AdventOfCodeBase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cs
108 lines (95 loc) · 3.36 KB
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AdventOfCode.Solutions.Year2020.Day21;
class Solution : SolutionBase
{
Dictionary<string, int> Ingredients = new();
Dictionary<string, HashSet<string>> ImplicatedIngredients = new();
public Solution() : base(21, 2020, "Allergen Assessment") { }
protected override string SolvePartOne()
{
Ingredients = new Dictionary<string, int>();
ImplicatedIngredients = new Dictionary<string, HashSet<string>>();
foreach (var (ingredients, allergens) in GetFoods())
{
foreach(var i in ingredients)
{
if (Ingredients.ContainsKey(i))
{
Ingredients[i]++;
}
else
{
Ingredients.Add(i, 1);
}
}
foreach (var a in allergens)
{
if (!ImplicatedIngredients.ContainsKey(a))
{
ImplicatedIngredients.Add(a, new HashSet<string>(ingredients));
}
else
{
ImplicatedIngredients[a] = ImplicatedIngredients[a].Intersect(ingredients).ToHashSet();
}
}
}
var allImplicatedIngredients = ImplicatedIngredients.Values.SelectMany(s => s).ToHashSet();
return Ingredients.Aggregate(0, (count, i) => allImplicatedIngredients.Contains(i.Key) ? count : count + i.Value).ToString();
}
protected override string SolvePartTwo()
{
Ingredients = new Dictionary<string, int>();
ImplicatedIngredients = new Dictionary<string, HashSet<string>>();
foreach (var (ingredients, allergens) in GetFoods())
{
foreach(var i in ingredients)
{
if (Ingredients.ContainsKey(i))
{
Ingredients[i]++;
}
else
{
Ingredients.Add(i, 1);
}
}
foreach (var a in allergens)
{
if (!ImplicatedIngredients.ContainsKey(a))
{
ImplicatedIngredients.Add(a, new HashSet<string>(ingredients));
}
else
{
ImplicatedIngredients[a] = ImplicatedIngredients[a].Intersect(ingredients).ToHashSet();
}
}
}
while (ImplicatedIngredients.Values.Any(v => v.Count > 1))
{
foreach (var (a, ingredients) in ImplicatedIngredients)
{
if (ingredients.Count == 1)
{
var i = ingredients.First();
foreach (var value in ImplicatedIngredients.Values)
{
if (value.Count == 1) continue;
value.Remove(i);
}
}
}
}
return ImplicatedIngredients.OrderBy(kv => kv.Key).Select(kv => kv.Value.First()).JoinAsStrings(",");
}
(string[] ingredients, string[] allergens)[] GetFoods()
=> Input.SplitByNewline().Select(l =>
{
var (ing, alg, _) = l.Split(" (contains ");
return (ing.Split(" "), alg.TrimEnd(')').Split(", "));
}).ToArray();
}