Daniel Tull: Advent of Code

Day 2: Dive!

Advent of Code 2021

Today we are given a set of instructions for manouvering the submarine. Although not as complicated as Day 8 last year my approach is pretty much the same, parse the input into a useable model and then act on it to generate the answer.

While it may not be as quick to type as parsing and execting in one step, I intentionally like to create an enum so my brain can process what it has to deal with.

enum Command {
    case up(Int)
    case down(Int)
    case forward(Int)
}

I then process these commands in a reduce function using a struct to hold the location of the sub.

try input.lines
    .map(Command.init)
    .reduce(into: Location()) { location, command in
        switch command {
        case .up(let amount): location.depth -= amount
        case .down(let amount): location.depth += amount
        case .forward(let amount): location.horizontal += amount
        }
    }
    .result