Skip to content

Instantly share code, notes, and snippets.

@ben0x539
Last active December 18, 2021 10:07
Show Gist options
  • Save ben0x539/095e28fffdd634c09a2becd572e854a8 to your computer and use it in GitHub Desktop.
Save ben0x539/095e28fffdd634c09a2becd572e854a8 to your computer and use it in GitHub Desktop.
def reduce(n)
while explode(n) || split(n)
end
n
end
def explode(n)
i = 0
depth = 0
while i < n.length
case n[i]
when '[' then depth += 1
when ']' then depth -= 1
end
if depth >= 5 && m = n[i..-1].match(/^\[(\d+),(\d+)\]/)
l, r = n[0...i], n[i+m[0].length..-1]
l.reverse!.sub!(/\d+/) { |c| (c.reverse.to_i + m[1].to_i).to_s.reverse }&.reverse!
r.sub!(/\d+/) { |c| (c.to_i + m[2].to_i).to_s }
n.replace(l + '0' + r)
return true
end
i += 1
end
return false
end
def split(n)
!!n.sub!(/\d\d+/) {|s| a = s.to_i/2; "[#{a},#{s.to_i - a}]"}
end
def magnitude(n)
while n.sub!(/\[(\d+),(\d+)\]/) { $1.to_i * 3 + $2.to_i * 2 }
end
n.to_i
end
def add(a, b)
reduce("[#{a},#{b}]")
end
if __FILE__ == $0
lines = STDIN.read.split
p magnitude(lines[1..-1].inject(lines[0]) {|a, b| add(a, b)})
p lines.map { |a| lines.filter_map { |b| a != b && magnitude(add(a, b)) } }.flatten.max
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment