2019/3/script.rb

50 lines
981 B
Ruby
Executable File

#!/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
def part1(path1, path2)
(path1 & path2).map { |coordinates| coordinates.map(&:abs).sum }.min
end
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 }
puts "=== Part 1 ==="
puts part1(path1, path2)
puts "=== Part 2 ==="
puts part2(path1, path2)