diff --git a/12/part1.py b/12/part1.py index 0f7c75e..2e21cc1 100644 --- a/12/part1.py +++ b/12/part1.py @@ -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 diff --git a/12/part2.py b/12/part2.py new file mode 100644 index 0000000..b0a7444 --- /dev/null +++ b/12/part2.py @@ -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)) \ No newline at end of file