Last active
October 29, 2019 12:31
-
-
Save AdrienGiboire/6a8017256ce29c392507a76b3db2ec7f to your computer and use it in GitHub Desktop.
Journeys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Robot | |
MOVES = { | |
L: 'move_left', | |
R: 'move_right', | |
F: 'move_forward' | |
} | |
DIRECTIONS = ['N', 'E', 'S', 'W'] | |
def initialize position | |
@coordinates = position.split(' ')[0, 2].map(&:to_i) | |
@direction = position.split(' ')[2] | |
end | |
def move moves | |
moves.split('').each do |move| | |
self.send(MOVES[move.to_sym]) | |
end | |
end | |
def move_right | |
index = (DIRECTIONS.find_index(@direction) + 1) % DIRECTIONS.count | |
@direction = DIRECTIONS[index] | |
end | |
def move_left | |
index = (DIRECTIONS.find_index(@direction) - 1) % DIRECTIONS.count | |
@direction = DIRECTIONS[index] | |
end | |
def move_forward | |
case @direction | |
when 'N' | |
@coordinates = [@coordinates[0], @coordinates[1] + 1] | |
when 'E' | |
@coordinates = [@coordinates[0] + 1, @coordinates[1]] | |
when 'S' | |
@coordinates = [@coordinates[0], @coordinates[1] - 1] | |
when 'W' | |
@coordinates = [@coordinates[0] - 1, @coordinates[1]] | |
end | |
end | |
def position | |
[@coordinates.flatten, @direction].join(' ') | |
end | |
end | |
inputs = [] | |
File.open('journeys.txt', 'r') do |file| | |
file.each_line do |line| | |
inputs << line.gsub("\n", "") | |
end | |
end | |
inputs.delete("") | |
inputs.each_slice(3).each do |slice| | |
wallee = Robot.new(slice[0]) | |
wallee.move(slice[1]) | |
puts "Actual: #{wallee.position}" | |
puts "Expected: #{slice[2]}" | |
puts wallee.position == slice[2] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment