Dive ! - Advent of Code Day 2

 

That ship got there by passing under the London Bridge 
- the vantage point for this photo
River Thames

In Day 2 of the Advent of Code problem we are given a starting position for the submarine, a set of commands, and 2 different ways of interpreting those commands (part a and part b)

Part A

For Part A, the commands indicate moves along the x and y axis for the given distance.

The code below loops through all the commands and executes the moves in the indicated direction and distance.

currentPos = (0,0)

for direction,dist in commands:
    x,y = { 'down' : (0,1) , 'forward' : (1,0) , 'up' : (0,-1) }[direction]
    currentPos = (currentPos[0] + (x*dist), currentPos[1] + (y*dist)) # move
    print(currentPos)

return currentPos

Part B

Part B changes the rules with up and down indicating that a third parameter aim is adjusted.  This parameter aim is used to adjust the position when a forward command is issued


The code below loops through the commands and only adjusts the aim if up or down is encountered. The current position is adjusted with every forward command.

currentPos = (0,0)
aim = 0

for direction,dist in commands:
    aim = aim + { 'down': dist , 'up' : -1 * dist , 'forward' : 0}[direction]
    if direction == 'forward':
        currentPos = (currentPos[0]+dist,currentPos[1]+(aim*dist))

return currentPos