Solved part 2 of day 12
This commit is contained in:
parent
e3d5e8b0c3
commit
33bfb88910
@ -42,9 +42,6 @@ if __name__ == "__main__":
|
||||
dirX, dirY = 0, 0
|
||||
if opcode == "F":
|
||||
dirX, dirY = degreesToOffset(currentDirection)
|
||||
elif opcode == "B":
|
||||
dirX, dirY = degreesToOffset(currentDirection)
|
||||
dirX, dirY = -dirX, -dirY
|
||||
else:
|
||||
dirX, dirY = directionToOffset(opcode)
|
||||
currentX += dirX * value
|
||||
|
53
12/part2.py
Normal file
53
12/part2.py
Normal file
@ -0,0 +1,53 @@
|
||||
import math
|
||||
|
||||
def getInstructions(filename):
|
||||
with open(filename, "r") as f:
|
||||
return [(line[0], int(line[1:])) for line in f.read().split()]
|
||||
|
||||
def directionToOffset(direction):
|
||||
if direction == "E":
|
||||
return (1, 0)
|
||||
elif direction == "N":
|
||||
return (0, -1)
|
||||
elif direction == "W":
|
||||
return (-1, 0)
|
||||
elif direction == "S":
|
||||
return (0, 1)
|
||||
else:
|
||||
raise Exception(f"Invalid cardinal direction '{direction}'")
|
||||
|
||||
def degreesToOffset(degrees):
|
||||
degrees %= 360
|
||||
if degrees == 0:
|
||||
return (1, 0)
|
||||
elif degrees == 90:
|
||||
return (0, -1)
|
||||
elif degrees == 180:
|
||||
return (-1, 0)
|
||||
elif degrees == 270:
|
||||
return (0, 1)
|
||||
else:
|
||||
raise Exception(f"Invalid degrees '{degrees}'")
|
||||
|
||||
def rotatePoint(x, y, angle):
|
||||
angleRadians = math.radians(angle)
|
||||
return round(x * math.cos(angleRadians) - y * math.sin(angleRadians)), \
|
||||
round(x * math.sin(angleRadians) + y * math.cos(angleRadians))
|
||||
|
||||
if __name__ == "__main__":
|
||||
currentX, currentY = 0, 0
|
||||
waypointX, waypointY = 10, -1
|
||||
for instruction in getInstructions("input.txt"):
|
||||
opcode, value = instruction
|
||||
if opcode == "F":
|
||||
currentX += waypointX * value
|
||||
currentY += waypointY * value
|
||||
elif opcode == "L":
|
||||
waypointX, waypointY = rotatePoint(waypointX, waypointY, -value)
|
||||
elif opcode == "R":
|
||||
waypointX, waypointY = rotatePoint(waypointX, waypointY, value)
|
||||
else:
|
||||
offX, offY = directionToOffset(opcode)
|
||||
waypointX += offX * value
|
||||
waypointY += offY * value
|
||||
print(abs(currentX) + abs(currentY))
|
Loading…
Reference in New Issue
Block a user