solved both parts

master^2
Jeff Yates 2 years ago
parent 28942a2c81
commit 6a41c0a0fe
  1. 47
      day12/solution1.rb
  2. 70
      day12/solution2.rb

@ -0,0 +1,47 @@
#!/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

@ -0,0 +1,70 @@
#!/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
def rotate (direction, degree, waypoint)
degree = degree / 90
degree.times do
waypoint[:x_position], waypoint[:y_position] =
waypoint[:y_position], (waypoint[:x_position])
waypoint[:y_position] *= -1 if direction =='R'
waypoint[:x_position] *= -1 if direction == 'L'
end
return waypoint
end
ship = {
:facing => :east,
:x_position => 0,
:y_position => 0
}
waypoint = {
:x_position => 10,
:y_position => 1
}
directions = File.read('./input').split("\n")
directions.each do |direction|
instruction = direction[0]
count = direction[1..-1].to_i
p [instruction, count]
case instruction
when 'F'
count.times do
ship[:x_position] += waypoint[:x_position]
ship[:y_position] += waypoint[:y_position]
end
when 'N'
waypoint[:y_position] += count
when 'S'
waypoint[:y_position] -= count
when 'E'
waypoint[:x_position] += count
when 'W'
waypoint[:x_position] -= count
when 'R','L'
waypoint = rotate(instruction, count, waypoint)
end
pp ship
end
manhattan = ship[:x_position].abs + ship[:y_position].abs
p manhattan
#binding.pry
Loading…
Cancel
Save