-
Notifications
You must be signed in to change notification settings - Fork 0
/
adventOfCode2020day7part2.linq
96 lines (80 loc) · 1.72 KB
/
adventOfCode2020day7part2.linq
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
<Query Kind="Program" />
const string targetBag = "shinygold";
Dictionary<string, Bag> dic;
void Main()
{
dic = new Dictionary<string, Bag>();
var input = ReadMyFile(@"input7.txt");
var list = ParseInput(input);
FollowBag(targetBag).Dump();
}
private int FollowBag(string bag)
{
var counter = 0;
if (bag != targetBag && dic.ContainsKey(bag))
{
counter++;
}
if (dic.ContainsKey(bag) && dic[bag].Holds.Any())
{
foreach (var newBag in dic[bag].Holds)
{
for (int i = 0; i < newBag.Item2; i++)
{
counter += FollowBag(newBag.Item1);
}
}
}
return counter;
}
private List<Bag> ParseInput(List<string> inputs)
{
var list = new List<Bag>();
foreach (var input in inputs)
{
var bag = new Bag(input);
if (!dic.ContainsKey(bag.Name))
{
dic.Add(bag.Name, bag);
}
list.Add(bag);
}
return list;
}
class Bag
{
public string Name { get; set; }
public List<(string, int)> Holds { get; set; }
public Bag(string input)
{
Holds = new List<(string, int)>();
var strs = input.Split(' ');
Name = CreateName(strs[0] + strs[1]);
int location = 7;
if (strs[3].Equals("contain"))
{
while (location < strs.Count() && (strs[location].Contains(",") || strs[location].Contains(".")))
{
Holds.Add((CreateName(strs[location - 2] + strs[location - 1]), int.Parse(strs[location - 3])));
location += 4;
if (location > strs.Count() - 1)
break;
}
}
}
private string CreateName(string name)
{
return name.Replace(",", "").Replace(".", "");
}
}
private List<string> ReadMyFile(string uri)
{
var newList = new List<string>();
string line;
System.IO.StreamReader reader = new StreamReader(uri);
while ((line = reader.ReadLine()) != null)
{
newList.Add(line);
}
return newList;
}