43 lines
838 B
Ruby
43 lines
838 B
Ruby
|
require "set"
|
||
|
|
||
|
input = STDIN.read.chomp
|
||
|
commands = input.split ", "
|
||
|
|
||
|
position = [0, 0] # Cartesian coordinates, +x is right, +y is up
|
||
|
direction = 0 # North I guess
|
||
|
|
||
|
visited_positions = Set.new([position.clone])
|
||
|
first_revisited_position = nil
|
||
|
|
||
|
commands.each do |command|
|
||
|
turn = command[0] == "L" ? 1 : -1
|
||
|
distance = command[1..].to_i
|
||
|
direction += turn
|
||
|
direction = direction % 4
|
||
|
|
||
|
distance.times do
|
||
|
case direction
|
||
|
when 0
|
||
|
position[1] += 1
|
||
|
when 1
|
||
|
position[0] += 1
|
||
|
when 2
|
||
|
position[1] -= 1
|
||
|
when 3
|
||
|
position[0] -= 1
|
||
|
end
|
||
|
|
||
|
if !visited_positions.add?(position.clone)
|
||
|
if first_revisited_position.nil?
|
||
|
first_revisited_position = position.clone
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
|
||
|
part_1 = position.map(&:abs).sum
|
||
|
part_2 = first_revisited_position.map(&:abs).sum
|
||
|
|
||
|
puts "Part 1: #{part_1}"
|
||
|
puts "Part 2: #{part_2}"
|