AoC2020/day12/solution1.rb

47 lines
1.0 KiB
Ruby
Executable File

#!/bin/env ruby
require 'pry'
def turn_ship (direction, degree, facing)
dirs = [:north, :east, :south, :west]
degree = degree / 90
degree = -degree if direction == 'L'
spin = dirs.find_index(facing) + degree
spin -= 4 if spin > 3
spin += 4 if spin < 0
return dirs[spin]
end
ship = {
:facing => :east,
:x_position => 0,
:y_position => 0 }
directions = File.read('./input').split("\n")
directions.each do |direction|
instruction = direction[0]
count = direction[1..-1].to_i
instruction = ship[:facing].to_s[0].upcase if instruction == 'F'
p [instruction, count]
case instruction
when 'N'
ship[:y_position] += count
when 'S'
ship[:y_position] -= count
when 'E'
ship[:x_position] += count
when 'W'
ship[:x_position] -= count
when 'R','L'
ship[:facing] = turn_ship(instruction, count, ship[:facing])
end
pp ship
end
manhattan = ship[:x_position].abs + ship[:y_position].abs
p manhattan
#binding.pry