Skip to content

Instantly share code, notes, and snippets.

@vincentwoo
Created December 23, 2018 23:01
Show Gist options
  • Save vincentwoo/800186bb8835faa691d5ef0eeb823793 to your computer and use it in GitHub Desktop.
Save vincentwoo/800186bb8835faa691d5ef0eeb823793 to your computer and use it in GitHub Desktop.
def run input
input = input.split("\n")
bots = input.map { |str|
pos, r = str.split(', ')
pos = pos[5..-2].split(',').map(&:to_i)
r = r.split('=').last.to_i
[pos, r]
}
xmin, xmax = bots.map(&:first).map(&:first).sort.values_at(0, -1)
ymin, ymax = bots.map(&:first).map {|_,y,_| y }.sort.values_at(0, -1)
zmin, zmax = bots.map(&:first).map(&:last).sort.values_at(0, -1)
counts = {}
increment = 10000000
round = -7
i = 0
x = xmin.round round
while x < xmax
y = ymin.round round
while y < ymax
z = zmin.round round
while z < zmax
pos = [x,y,z]
counts[pos] = bots.select { |bot_pos, r| distance(pos, bot_pos) <= r }
i += 1
z += increment
end
y += increment
end
x += increment
end
max_count = counts.values.map(&:length).max
coords, bots = counts.select { |k ,v | v.length == max_count }.first
while increment > 1
tests = coords.map { |c| ((c - increment)..(c + increment)).step(increment / 10).to_a }
tests = tests[0].product(tests[1], tests[2])
tests.select! { |coord| bots.all? { |bot_pos, r| distance(coord, bot_pos) <= r } }
coords = tests.min_by(&:sum)
increment /= 10
end
p coords.sum
end
def distance p1, p2
(p1[0] - p2[0]).abs + (p1[1] - p2[1]).abs + (p1[2] - p2[2]).abs
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment