Skip to content

Instantly share code, notes, and snippets.

@manlon
Created December 7, 2017 09:43
Show Gist options
  • Save manlon/3bee2daee60451884752ab894cd1d116 to your computer and use it in GitHub Desktop.
Save manlon/3bee2daee60451884752ab894cd1d116 to your computer and use it in GitHub Desktop.
class AoC7
attr_reader :weights, :child_map, :root_name
PATTERN = /^([a-z]+) \(([0-9]+)\)( -> ([a-z ,]+))?$/
def initialize
lines = IO.read("./input7.txt").strip.split("\n")
@weights = {}
@child_map = {}
lines.each do |line|
PATTERN =~ line
@weights[$1] = $2.to_i
@child_map[$1] = ($4 || "").split(", ")
end
all_children = @child_map.values.flatten
@root_name = @weights.keys.find{|k| @child_map[k].size > 0 && !all_children.member?(k)}
end
def find_imbalance(name=nil)
name ||= @root_name
children = @child_map[name]
if children.empty?
return [name, @weights[name]]
end
child_results = children.collect{|n| find_imbalance(n)}
child_weights = child_results.collect(&:last)
if child_weights.uniq.size == 1
return [name, @weights[name] + child_weights.inject(&:+)]
else
loner_weight, good_weight = child_weights.partition{|w| w == child_weights.first}.sort_by(&:size).collect(&:first)
loner_name = child_results.find{|name, weight| weight == loner_weight}.first
diff = loner_weight - good_weight
raise (weights[loner_name] - diff).to_s
end
end
end
AoC7.new.tap{|x| puts x.root_name}.find_imbalance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment