Skip to content

Instantly share code, notes, and snippets.

@AdrienGiboire
Last active October 29, 2019 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdrienGiboire/6a8017256ce29c392507a76b3db2ec7f to your computer and use it in GitHub Desktop.
Save AdrienGiboire/6a8017256ce29c392507a76b3db2ec7f to your computer and use it in GitHub Desktop.
Journeys
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