Advent of code - Day 2

Objective

Given a series of navigation directions find the final position of a submarine

Part 1

To solve this we define a navigate function that adjusts the location of the submarine.

def navigate(course: Course, loc: Point = Point(0, 0)):
    # Follow the course for the submarine and return the horizontal and vertical positions
    for direction, n in course:
        if direction == 'forward':
            loc.x += n
        elif direction == 'down':
            loc.y += n
        elif direction == 'up':
            loc.y -= n

    return loc


def day2_1(course: Course):
    loc = navigate(course)
    return loc.x * loc.y

Part 2

For part 2 we use a modified navigate function that also adjusts the aim of the submarine.

def navigate_with_aim(course: Course, loc: Point = Point(0, 0, 0)):
    # Follow the course for the submarine and return the horizontal and vertical positions
    for direction, n in course:
        if direction == 'forward':
            loc.x += n
            loc.y += n * loc.aim
        elif direction == 'down':
            loc.aim += n
        elif direction == 'up':
            loc.aim -= n

    return loc


def day2_2(course: Course):
    loc = navigate_with_aim(course)
    return loc.x * loc.y
Dwight Gunning

Dwight Gunning