2019-12-12 17:32:24 +01:00
|
|
|
#!/usr/bin/env ruby
|
|
|
|
|
|
|
|
require_relative '../common'
|
|
|
|
|
|
|
|
class Path
|
|
|
|
attr_reader :path
|
|
|
|
|
|
|
|
def initialize(path)
|
|
|
|
@path = path.split(',')
|
|
|
|
@x = @y = 0
|
|
|
|
end
|
|
|
|
|
|
|
|
def coordinates
|
|
|
|
@coordinates ||= path.inject([]) do |result, move|
|
|
|
|
direction = move[0]
|
|
|
|
count = move[1..].to_i
|
|
|
|
result + count.times.map { |i| move(direction) }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def move(direction)
|
|
|
|
if direction == "L"
|
|
|
|
@x -= 1
|
|
|
|
elsif direction == "R"
|
|
|
|
@x += 1
|
|
|
|
elsif direction == "D"
|
|
|
|
@y += 1
|
|
|
|
elsif direction == "U"
|
|
|
|
@y -= 1
|
|
|
|
end
|
|
|
|
|
|
|
|
[@x, @y]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2019-12-21 11:15:17 +01:00
|
|
|
def part1(path1, path2)
|
2019-12-12 17:32:24 +01:00
|
|
|
(path1 & path2).map { |coordinates| coordinates.map(&:abs).sum }.min
|
|
|
|
end
|
|
|
|
|
2019-12-21 11:15:17 +01:00
|
|
|
def part2(path1, path2)
|
|
|
|
(path1 & path2).map { |coordinates| path1.index(coordinates) + path2.index(coordinates) + 2 }.min
|
|
|
|
end
|
|
|
|
|
|
|
|
path1, path2 = Input.new(__dir__).readlines.map { |line| Path.new(line).coordinates }
|
|
|
|
|
2019-12-12 17:32:24 +01:00
|
|
|
puts "=== Part 1 ==="
|
2019-12-21 11:15:17 +01:00
|
|
|
puts part1(path1, path2)
|
|
|
|
puts "=== Part 2 ==="
|
|
|
|
puts part2(path1, path2)
|