Skip to content

Instantly share code, notes, and snippets.

@teddywing
Last active September 3, 2015 06:05
Show Gist options
  • Save teddywing/f7c56beff41106a97d34 to your computer and use it in GitHub Desktop.
Save teddywing/f7c56beff41106a97d34 to your computer and use it in GitHub Desktop.
Robot movement
#!/usr/bin/env python
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.x, self.y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return self.x != other.x or self.y != other.y
class Position(object):
NORTH = 'n'
EAST = 'e'
SOUTH = 's'
WEST = 'w'
def __init__(self, location, orientation):
self.location = location
self.orientation = orientation
class Robot(object):
def __init__(self):
self.location = Point(0, 0)
self.orientation = Position.NORTH
def go(self):
if self.orientation == Position.NORTH:
self.location = Point(self.location.x, self.location.y - 1)
elif self.orientation == Position.EAST:
self.location = Point(self.location.x + 1, self.location.y)
elif self.orientation == Position.SOUTH:
self.location = Point(self.location.x, self.location.y + 1)
elif self.orientation == Position.WEST:
self.location = Point(self.location.x - 1, self.location.y)
def turn_right(self):
if self.orientation == Position.NORTH:
self.orientation = Position.EAST
elif self.orientation == Position.EAST:
self.orientation = Position.SOUTH
elif self.orientation == Position.SOUTH:
self.orientation = Position.WEST
elif self.orientation == Position.WEST:
self.orientation = Position.NORTH
def turn_left(self):
if self.orientation == Position.NORTH:
self.orientation = Position.WEST
elif self.orientation == Position.EAST:
self.orientation = Position.NORTH
elif self.orientation == Position.SOUTH:
self.orientation = Position.EAST
elif self.orientation == Position.WEST:
self.orientation = Position.SOUTH
def circle_does_exist(commands):
robot = Robot()
steps = [Position(robot.location, robot.orientation)]
for c in commands:
if c == 'G':
robot.go()
steps.append(Position(robot.location, robot.orientation))
elif c == 'R':
robot.turn_right()
elif c == 'L':
robot.turn_left()
# If the starting position is the same as the ending position, we are in
# a circle that the bot never leaves.
#
# NOTE: This isn't correct and doesn't find all the possible circular paths
if steps[0].location == steps[-1].location:
return 'YES'
return 'NO'
print(circle_does_exist('GRGGRGGRGRGLG'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment