AdventOfCode-2017/day3_1.rb

27 lines
929 B
Ruby

def corner_num(corner)
return corner**2 - corner
end
puzzle_input = 289326
corner = (1 + Math.sqrt(1 + 4*(puzzle_input - 1))) / 2
puts corner
next_corner = corner_num(corner.ceil)
prev_corner = corner_num(corner.floor)
distance = 0
if(next_corner == prev_corner) then
distance = 2*((corner / 2).floor)
else
halfway_point = (next_corner + prev_corner) / 2
edge_length = next_corner - halfway_point
start_from = (puzzle_input > halfway_point) ? halfway_point : prev_corner
progress = (puzzle_input - 1 - start_from).to_f / edge_length
if(corner.floor % 2 == 1 and puzzle_input < halfway_point) then distance -= 1 end
previous_distance = (corner.ceil / 2).floor
next_distance = ((corner.floor)/2).floor
puts previous_distance
puts next_distance
distance += (corner / 2).floor
distance += (-previous_distance + (previous_distance + next_distance)*progress).abs
end
puts distance