Skip to content

Instantly share code, notes, and snippets.

@nudded
Created December 7, 2017 19:43
Show Gist options
  • Save nudded/d991e4dedf8ba3338f09266aed8479d4 to your computer and use it in GitHub Desktop.
Save nudded/d991e4dedf8ba3338f09266aed8479d4 to your computer and use it in GitHub Desktop.
day7.rb
input = File.readlines("inputs/day7.in")
DISCS = {}
class Disc < Struct.new(:name, :weight, :children, :parent)
def subtree_weight
return weight unless children
children.map {|c| DISCS[c].subtree_weight}.inject(0) {|a,b| a+b} + weight
end
end
input.each do |line|
disc = if line =~ /^(\w+) \((\d+)\) -> (.+)$/
Disc.new $1, $2.to_i, $3.split(',').map(&:strip)
elsif line =~ /^(\w+) \((\d+)\)$/
Disc.new($1, $2.to_i)
end
DISCS[disc.name] = disc
end
DISCS.values.each do |disc|
children = disc.children
next unless children
children.each {|name| DISCS[name].parent = disc}
end
root = DISCS.values.detect {|d| d.parent.nil? }
puts "root: #{root.name}"
def find_element_with_other_weigth(root)
hash = Hash.new {|h,k| h[k] = Array.new}
root.children.each do | c|
disc = DISCS[c]
hash[disc.subtree_weight] << disc
end
key, value = hash.detect {|k,v| v.size == 1}
if value
find_element_with_other_weigth(value.first)
else
root
end
end
wrong = find_element_with_other_weigth(root)
other_element = DISCS[wrong.parent.children.detect {|c| c != wrong.name}]
puts "correct weight: #{wrong.weight - (wrong.subtree_weight - other_element.subtree_weight)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment