Skip to content

Instantly share code, notes, and snippets.

@tecoholic
Created May 29, 2015 18:25
Show Gist options
  • Save tecoholic/ed55cd87059abbb16362 to your computer and use it in GitHub Desktop.
Save tecoholic/ed55cd87059abbb16362 to your computer and use it in GitHub Desktop.
###############################################################################
# Filename: marsrover.py
# Author: Arunmozhi
# Email: [email protected]
# Date: 29 May 2015
###############################################################################
import sys
class Rover:
def __init__(self,pos):
self.x = int(pos[0])
self.y = int(pos[1])
self.d = pos[2]
self.directions = ['N','E', 'S', 'W']
def turn_left(self):
if self.directions.index(self.d) == 0:
self.d = self.directions[3]
else:
self.d = self.directions[self.directions.index(self.d)-1]
def turn_right(self):
if self.directions.index(self.d) == 3:
self.d = self.directions[0]
else:
self.d = self.directions[self.directions.index(self.d)+1]
def move(self):
if self.d == 'N':
self.y += 1
elif self.d == 'S':
self.y -= 1
elif self.d == 'E':
self.x += 1
else:
self.x -= 1
def follow_instructions(self, ins):
steps = list(ins.strip())
for step in steps:
if step == 'L':
self.turn_left()
elif step == 'R':
self.turn_right()
elif step == 'M':
self.move()
def run_rovers(filename):
plat_x = 0
plat_y = 0
infile = open(filename, 'r')
outfile = open("output.txt", 'w')
parts = infile.readline().split()
plat_x = int(parts[0])
plat_y = int(parts[1])
# create the first rover object so others can be iteratively overwritten
rover = Rover(infile.readline().split())
nextIsRover = False
# read two lines at a time and plot rover positions
for line in infile:
if nextIsRover:
rover = Rover(line.split())
nextIsRover = False
else:
rover.follow_instructions(line)
if 0 <= rover.x <= plat_x and 0 <= rover.y <= plat_y:
outfile.write(" ".join([str(rover.x), str(rover.y), rover.d])+"\n")
else:
outfile.write("Sorry, this rover is off the plateau and lying in the valley :(\n")
nextIsRover = True
infile.close()
outfile.write('============\n')
outfile.close()
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Usage: python marsrover.py <filename>"
else:
run_rovers(sys.argv[1])
print "The current locations of mars rovers can be read from <output.txt>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment