Skip to content

Instantly share code, notes, and snippets.

@pjhoberman
Created December 14, 2020 20:58
Show Gist options
  • Save pjhoberman/e83331ceabc10c986059c83acbfac193 to your computer and use it in GitHub Desktop.
Save pjhoberman/e83331ceabc10c986059c83acbfac193 to your computer and use it in GitHub Desktop.
with open('data.txt') as file:
data = file.read().splitlines()
# part 1
DIRECTIONS = {
0: 'N',
90: 'E',
180: 'S',
270: 'W',
}
class Ship:
def __init__(self):
self.bearing = 90
self.position = {"E": 0, "N": 0}
def move(self, direction, units):
print(f"Moving {direction} {units}")
if direction in ["L", "R"]:
new_bearing = (self.bearing + units) % 360 if direction == "R" else (self.bearing - units) % 360
self.bearing = new_bearing
print(self)
elif direction in ["E", "W", "N", "S"]:
if direction == "E":
self.position['E'] += units
elif direction == "W":
self.position['E'] -= units
elif direction == "N":
self.position['N'] += units
elif direction == "S":
self.position['N'] -= units
print(self)
# forward
else:
self.move(DIRECTIONS[self.bearing], units)
def manhattan(self):
return abs(self.position['E']) + abs(self.position['N'])
def __str__(self):
return f"bearing: {self.bearing}\nposition: {self.position}"
dirs = ['F10', 'N3', 'F7', 'R90', 'F11']
ship = Ship()
for d in dirs:
ship.move(d[0], int(d[1:]))
assert ship.manhattan() == 25
# part 2
class Ship:
def __init__(self):
self.bearing = 0
self.position = {"E": 0, "N": 0}
self.waypoint = {"E": 10, "N": 1}
def move(self, direction, units):
if direction in ["L", "R"]:
new_bearing = (self.bearing + units) % 360 if direction == "R" else (self.bearing - units) % 360
while self.bearing != new_bearing:
self.waypoint = {'E': self.waypoint['N'] * -1, 'N': self.waypoint['E']}
self.bearing -= 90
if self.bearing >= 360:
self.bearing = 0
if self.bearing < 0:
self.bearing = 270
elif direction in ["E", "W", "N", "S"]:
if direction == "E":
self.waypoint['E'] += units
elif direction == "W":
self.waypoint['E'] -= units
elif direction == "N":
self.waypoint['N'] += units
elif direction == "S":
self.waypoint['N'] -= units
# forward
else:
self.position['E'] += self.waypoint['E'] * units
self.position['N'] += self.waypoint['N'] * units
def manhattan(self):
return abs(self.position['E']) + abs(self.position['N'])
def __str__(self):
return f"bearing: {self.bearing}\nposition: {self.position}\nwaypoint: {self.waypoint}"
dirs = ['F10', 'N3', 'F7', 'R90', 'F11']
ship = Ship()
for d in dirs:
ship.move(d[0], int(d[1:]))
assert ship.manhattan() == 286
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment