Advent of Code 2021, Day 2

Andrew Fontaine <andrew@afontaine.ca>

Now that I know where I am going, I get to figure out how to pilot the submarine! The first puzzle is perfect for List.fold_left:

let follow_instruction (x, y) (dir, num)   match dir with
  | "up" -> (x, y - num)
  | "down" -> (x, y + num)
  | "forward" -> (x + num, y)
  | direction -> raise (Direction direction)

let p1_sol input   let x, y = List.fold_left follow_instruction (0, 0) input in
  x * y

I just match on the direction I am going and increment the correct direction. All that’s left is to compute the answer (multiply the coordinates together).

If I just match on the four directions, up, down, forward, then ocaml complains that the match is not fully matched. Its type system does not allow for uncaught matches, which are dependent on the type of the variable. Here, the uncaught matches are literally every string of characters that isn’t one of the directions. The correct answer is to parse these directions into a variant, a plain symbol-thing that is a specific set of options: Up | Down | Forward, and lift this error up to where I parse the line. I didn’t do that though, so I have to check it here and throw if it is incorrect. As I feel very confident here that it would not be, I think I am pretty safe.

☆ one done!

Part 2

Ah! Turns out I was interpreting the instructions wrong. It isn’t exactly up or down, but changing the aim of the submarine up or down. This is a pretty simple adjustment, all I have to do is add the aim to the result tuple to keep track of it:

let follow_instruction_2 (x, y, a) (dir, num)   match dir with
  | "up" -> (x, y, a - num)
  | "down" -> (x, y, a + num)
  | "forward" -> (x + num, y + (a * num), a)
  | direction -> raise (Direction direction)

let p2_sol input   let x, y, _ = List.fold_left follow_instruction_2 (0, 0, 0) input in
  x * y

The same problem as above, I should be using variants. We can see though that just adjusting the aim to handle the new up and down (adjust the nose by the number) and forward (now including the submarine’s current aim multiplied by how far forward). When I compute the value, because I don’t use the aim, I use the _ variable to note that the variable is not used.

Hopefully now the submarine is on the way to find those keys!


Want to discuss this post?

Reach out via email to ~afontaine/blog-discuss@lists.sr.ht, and be sure to follow the mailing list etiquette.

Other posts