Advent of Code - Day 2

Wed, Dec 08 2021

Day Two - Part A

The day two problem was determining a location using a horizontal position and depth. The only tricky thing was that the up and down values decreased and increased the depth, respectively. The data file looks like this:

[ forward: 9, down: 8, down: 2, down: 4, up: 8, forward: 8, down: 7, forward: 3, down: 8 ...]

I am sticking with recursion as my go-to tool, so I started with my exit function.

def adjust_location([], horizontal, depth), do: horizontal * depth

Starting with horizontal: 0 and depth: 0, I need to match the action and adjust the appropriate value.

def adjust_location([], horizontal, depth), do: horizontal * depth

def adjust_location([{:forward, amt} | t], horizontal, depth), do: assess(t, h + amt, depth)

def adjust_location([{:down, amt} | t], horizontal, d), do: assess(t, horizontal, depth + amt)

def adjust_location([{:up, amt} | t], horizontal, depth), do: assess(t, horizontal, depth - amt)

To run the code, I call it with the starting values Advant.adjust_location(directions(), 0, 0). This works nicely, and the answer is correct :)

Day Two - Part B

The second part of the problem is a little more complex.

In addition to horizontal position and depth, you’ll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought:

  • down X increases your aim by X units.
  • up X decreases your aim by X units.
  • forward X does two things:
  • It increases your horizontal position by X units.
  • It increases your depth by your aim multiplied by X.

Fortunately, it is too different from Part A. I was able to add another accumulator to my function signature and update the logic. So my exit function is the same but with an unused arg.

def adjust_location_with_aim([], horizontal, depth, _aim), do: horizontal * depth

The recursive functions needed a slight adjustment to match the new rules.

def adjust_location_with_aim([], horizontal, depth, _aim), do: horizontal * depth

def adjust_location_with_aim([{:forward, amt} | t], horizontal, depth, aim), do: adjust_location_with_aim(t, horizontal + amt, depth + (aim * amt), aim)

def adjust_location_with_aim([{:down, amt} | t], horizontal, depth, aim), do: adjust_location_with_aim(t, horizontal, depth, aim+ amt)

def adjust_location_with_aim([{:up, amt} | t], horizontal, depth, aim), do: adjust_location_with_aim(t, horizontal, depth, aim- amt)

Running this code Advant.adjust_location(directions(), 0, 0, 0) works perfectly.