diff --git a/day12/solution1.rb b/day12/solution1.rb new file mode 100755 index 0000000..26270ae --- /dev/null +++ b/day12/solution1.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 \ No newline at end of file diff --git a/day12/solution2.rb b/day12/solution2.rb new file mode 100755 index 0000000..8d30cee --- /dev/null +++ b/day12/solution2.rb @@ -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 \ No newline at end of file