Created
December 8, 2016 23:03
-
-
Save fuzzmonkey/2570894a412f080bb21f374f2ea8f6fe to your computer and use it in GitHub Desktop.
robots! ruby!
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 | |
DIRECTIONS = { | |
1 => "NORTH", | |
2 => "EAST", | |
3 => "SOUTH", | |
4 => "WEST" | |
} | |
attr_accessor :grid_size, :x, :y, :facing | |
def initialize grid_size | |
@grid_size = grid_size | |
end | |
def parse_input str | |
str.split("\n").each do |line| | |
cmd, args = line.split(" ") | |
args = args.to_s.split(",") | |
self.send cmd.downcase.to_sym, *args | |
end | |
end | |
def left | |
rotate -1 | |
end | |
def right | |
rotate +1 | |
end | |
def rotate modifier | |
return unless placed? | |
idx = DIRECTIONS.key(facing) | |
next_dir_idx = idx + modifier | |
next_dir_idx = 1 if next_dir_idx > 4 | |
next_dir_idx = 4 if next_dir_idx < 1 | |
@facing = DIRECTIONS[next_dir_idx] | |
end | |
def move | |
return unless placed? | |
x_, y_ = x, y | |
case facing | |
when "NORTH" | |
y_ = y + 1 | |
when "SOUTH" | |
y_ = y - 1 | |
when "EAST" | |
x_ = x + 1 | |
when "WEST" | |
x_ = x - 1 | |
end | |
if valid_move?(x_, y_) | |
@x = x_ | |
@y = y_ | |
end | |
end | |
def place x, y, direction | |
x = x.to_i | |
y = y.to_i | |
return unless valid_move?(x, y) && valid_direction?(direction) | |
@x = x | |
@y = y | |
@facing = direction | |
end | |
def report | |
return [x, y, facing].join(",") | |
end | |
def placed? | |
!x.nil? && !y.nil? | |
end | |
def valid_move? x, y | |
return (0...grid_size-1) === x && (0...grid_size-1) === y | |
end | |
def valid_direction? direction | |
return DIRECTIONS.values.include?(direction) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment