Skip to content

Instantly share code, notes, and snippets.

@steveh
Created December 1, 2016 20:02
Show Gist options
  • Save steveh/9763bc33c73f9395704511869b4e9fa9 to your computer and use it in GitHub Desktop.
Save steveh/9763bc33c73f9395704511869b4e9fa9 to your computer and use it in GitHub Desktop.
require "set"
Command = Struct.new(:direction, :blocks)
class Compass
BEARINGS = [:north, :east, :south, :west]
def initialize
@index = 0
end
def left
if index == 0
self.index = BEARINGS.length - 1
else
self.index -= 1
end
BEARINGS[self.index]
end
def right
if index == BEARINGS.length - 1
self.index = 0
else
self.index += 1
end
BEARINGS[self.index]
end
protected
attr_accessor :index
end
pattern = /([LR])(\d+)/
commands = File.read("input.txt").split(", ").collect do |str|
if str =~ pattern
Command.new($1.to_sym, $2.to_i)
else
raise "nah bro"
end
end
compass = Compass.new
visited_points = Set.new
current_point = [0,0]
commands.each do |command|
bearing = case command.direction
when :L then compass.left
when :R then compass.right
else raise ArgumentError, "Unknown direction"
end
axis_index = case bearing
when :north, :south then 0
when :east, :west then 1
end
operator = case bearing
when :east, :south then :+
when :west, :north then :-
end
# puts "turn #{command.direction}, now facing #{bearing}, move #{command.blocks} blocks"
command.blocks.times do
current_point[axis_index] = current_point[axis_index].public_send(operator, 1)
puts "#{current_point}"
if visited_points.include?(current_point)
puts "visited twice! #{current_point.inspect}"
puts current_point.collect(&:abs).inject(0, &:+)
exit
end
visited_points << current_point
end
end
puts current_point.inspect
puts current_point.collect(&:abs).inject(0, &:+)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment