-
Notifications
You must be signed in to change notification settings - Fork 1
/
day7.rb
79 lines (67 loc) · 1.49 KB
/
day7.rb
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
class Node
attr_accessor :name, :weight, :children
def initialize(name, weight, children = [])
@name = name
@weight = weight
@children = children
end
def branch_weight
@children.map do |c|
c.branch_weight
end.reduce(@weight, :+)
end
def common_children_weight
value_counter = Hash.new(0)
values = @children.map do |c|
c.branch_weight
end
values.each do |v|
value_counter[v] += 1
end
values.select do |v|
v if v != value_counter.key(1)
end[0]
end
def outlier
o = nil
@children.each do |c|
o = c if c.branch_weight != self.common_children_weight
end
o
end
end
def construct_tree(b_root)
if (ch = Branches[b_root]).nil?
children = []
else
children = ch.map do |c|
construct_tree(c)
end
end
Node.new(b_root, Weights[b_root], children)
end
def find_final_outlier(root)
outlier = root.clone
previous = nil
while not (outlier = outlier.outlier).nil?
previous = outlier.clone
end
previous
end
Branches = {}
Weights = {}
children = []
all = []
file = ARGV[0] || "input.txt"
open(file).each_line do |line|
a = line.gsub(/,/, "").split
Weights.merge!({ a[0] => Integer(a[1].gsub(/[()]/, "")) })
all << a[0]
if not a[3].nil?
Branches.merge!({ a[0] => a[3..a.count] })
children += a[3..a.count]
end
end
Root = construct_tree((all - children)[0])
puts Root.name
puts find_final_outlier(Root).weight + (Root.common_children_weight - Root.outlier.branch_weight)