Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Last active December 13, 2020 12:05
Show Gist options
  • Save MikeRogers0/7838dc0b8cb293046912127b28911bd7 to your computer and use it in GitHub Desktop.
Save MikeRogers0/7838dc0b8cb293046912127b28911bd7 to your computer and use it in GitHub Desktop.
AOC 2020 - Day 12, part 2
class Ship
def initialize
@x = 0
@y = 0
@waypoint_x = 10
@waypoint_y = 1
end
def rotate!(direction, degrees_to_turn)
puts "Waypoint was: #{current_waypoint}"
if direction == 'R'
(degrees_to_turn / 90).times do
tmp_y = @waypoint_y.dup
@waypoint_y = 0 - @waypoint_x
@waypoint_x = tmp_y
end
else
(degrees_to_turn / 90).times do
tmp_x = @waypoint_x.dup
@waypoint_x = 0 - @waypoint_y
@waypoint_y = tmp_x
end
end
puts "Waypoint is: #{current_waypoint}"
end
def forward!(distance)
@x += (@waypoint_x * distance)
@y += (@waypoint_y * distance)
puts "Moved to: #{current_position}"
end
def move_waypoint!(direction, distance)
if direction == 'N'
@waypoint_y += distance
elsif direction == 'S'
@waypoint_y -= distance
elsif direction == 'E'
@waypoint_x += distance
elsif direction == 'W'
@waypoint_x -= distance
end
puts "Waypoint is: #{current_waypoint}"
end
def current_waypoint
[
"X: #{@waypoint_x}",
"Y: #{@waypoint_y}"
]
end
def current_position
[
"X: #{@x}",
"Y: #{@y}"
]
end
def manhattan_position
@x.abs + @y.abs
end
end
class Command
def initialize(string)
@direction = string[0]
@distance = string[1..].to_i
end
def call(ship)
if @direction == 'R' || @direction == 'L'
ship.rotate!(@direction, @distance)
elsif @direction == 'F'
ship.forward!(@distance)
else
ship.move_waypoint!(@direction, @distance)
end
end
end
@ship = Ship.new
@commands = File.open('input.real.txt').read.split("\n").compact.each do |command|
puts command
Command.new(command).call(@ship)
puts ""
end
puts ""
puts "Manhatten Position: #{@ship.manhattan_position}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment