+/AoC

advent of code

git clone https://git.julia.blue/+/AoC

Joseph RyanStart 2018!38c0746

master
1.5 KiB58 linesraw
1from itertools import product
2
3
4class Program():
5
6    def __init__(self, n, w, c=[]):
7        self.name = n
8        self.weight = w
9        self.children = c
10
11    def updateChildren(self, proglist):
12        self.children = [i[1] for i in product(self.children, proglist) if i[0] == i[1].name]
13
14    def getTotalChildren(self):
15        return len(self.children) + sum(i.getTotalChildren() for i in self.children)
16
17    def updateTotalWeight(self):
18        self.totalWeight = self.weight + sum(i.updateTotalWeight() for i in self.children)
19        return self.totalWeight
20
21raw = map(lambda x: x.strip(), open("input.txt"))
22
23programs = []
24for line in raw:
25    line = line.replace(',', ' ').split()
26    programs.append(Program(line[0], int(line[1][1:-1]), line[3:]))
27
28for p in programs:
29    p.updateChildren(programs)
30
31programs.sort(key=lambda p: p.getTotalChildren())
32
33print "Part 1:", programs[-1].name
34
35programs[-1].updateTotalWeight()
36
37
38def balance(p, needs=0):
39    if not p.children:
40        return
41    if len(set([i.totalWeight for i in p.children])) == 1:
42        return
43
44    p.children.sort(key=lambda i: i.totalWeight)
45    if not needs:
46        needs = p.children[-1].totalWeight - p.children[0].totalWeight
47        if p.children[0].totalWeight == p.children[1].totalWeight:
48            needs = -needs
49
50    kidsresults = [balance(i, needs) for i in p.children]
51    if any(kidsresults):
52        return [i for i in kidsresults if i][0]
53
54    if needs > 0:
55        return p.children[0].weight + needs
56    return p.children[-1].weight + needs
57
58print "Part 2:", balance(programs[-1])