In [1]:
function read_tree(input_file)
open(input_file) do fd
fathers = Dict()
weights = Dict()
for line in eachline(fd)
name, weight, haschildren, children = match(r"([a-z]+) \(([0-9]+)\)( -> )?([a-z, ]*)", line).captures
weights[name] = parse(Int32, weight)
if !haskey(fathers, name)
fathers[name] = nothing
end
if haschildren != nothing
for child in split(children, ", ")
fathers[child] = name
end
end
end
for (name, father) in fathers
if father == nothing
return weights, fathers, name
end
end
end
end
Out[1]:
In [2]:
w, f, bottom = read_tree("inputs/day7.txt")
println("This is the bottom: ", bottom)
In [3]:
using DataStructures
function missing_weight(weights, fathers, name)
children = [child for (child, father) in fathers if father == name]
children_weights = map(n -> missing_weight(weights, fathers, n), children)
c = counter(children_weights)
if length(c)>1
if length(c) != 2
error("There are more than one unbalanced towers")
end
un_weight = collect(keys(c))[indmin(collect(values(c)))]
bl_weight = collect(keys(c))[indmax(collect(values(c)))]
un_child = children[findfirst(children_weights, un_weight)]
println("Unbalanced: '", un_child, "' it has to weight ", weights[un_child] + (bl_weight - un_weight))
throw(InterruptException())
end
weights[name] + (length(children_weights)>0?sum(children_weights):0)
end
Out[3]:
In [4]:
try
missing_weight(w, f, bottom)
catch InterruptException
end
In [ ]: