60 lines
1.3 KiB
Python
60 lines
1.3 KiB
Python
|
class Ferry:
|
||
|
def __init__(self):
|
||
|
self.heading = 90 # east
|
||
|
self.pos_north = 0
|
||
|
self.pos_east = 0
|
||
|
|
||
|
def load(self, filename):
|
||
|
with open(filename, "r", encoding="utf-8") as f:
|
||
|
for line in f:
|
||
|
data = line.rstrip()
|
||
|
self.process(data)
|
||
|
|
||
|
def rotate(self, degrees):
|
||
|
self.heading += degrees
|
||
|
while self.heading < 0:
|
||
|
self.heading += 360
|
||
|
while self.heading >= 360:
|
||
|
self.heading -= 360
|
||
|
|
||
|
def process(self, input):
|
||
|
command = input[:1]
|
||
|
value = int(input[1:])
|
||
|
|
||
|
if command == "N":
|
||
|
self.pos_north += value
|
||
|
elif command == "S":
|
||
|
self.pos_north -= value
|
||
|
elif command == "E":
|
||
|
self.pos_east += value
|
||
|
elif command == "W":
|
||
|
self.pos_east -= value
|
||
|
elif command == "L":
|
||
|
self.rotate(-value)
|
||
|
elif command == "R":
|
||
|
self.rotate(value)
|
||
|
elif command == "F":
|
||
|
if self.heading == 0:
|
||
|
self.pos_north += value
|
||
|
elif self.heading == 90:
|
||
|
self.pos_east += value
|
||
|
elif self.heading == 180:
|
||
|
self.pos_north -= value
|
||
|
elif self.heading == 270:
|
||
|
self.pos_east -= value
|
||
|
else:
|
||
|
raise Exception(self.heading)
|
||
|
else:
|
||
|
raise Exception(command)
|
||
|
|
||
|
print(input, self.pos_east, self.pos_north)
|
||
|
|
||
|
def get_md(self):
|
||
|
return abs(self.pos_east) + abs(self.pos_north)
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
f = Ferry()
|
||
|
f.load("data.txt")
|
||
|
md = f.get_md()
|
||
|
print(f"Manhattan distance is {md}")
|