Advent of Code Day 3 – Mull It Over

Today’s puzzle was about parsing. Quite straightforward to implement, having done parsing earlier for different types of structured strings, like tsv, csv, json, xml, etc.

In part 1, I anticipated that part 2 would add parsing some other instructions than mul so I did implement it so. There is an Instruction structure that specifies:

  • the instruction name
  • expected number of parameters and
  • the list of parameter values

Then the instruction is able to evaluate the result. Parsing returns an array of Instructions to execute, and then they are executed, accumulating the result of each mul instruction evaluated:

private struct Instruction {
  let instruction: String
  let params: Int
  var values: [Int] = []
    
  var result: Int {
    if instruction == "mul" {
      return values.reduce(1, *)
    }
    return 0
  }
}

In part 2, the execution just changes the state; after do instruction, following instructions are evaluated, and after don't, the instructions are ignored, until next do instruction:

func part1() -> Any {
    let instructions = parse(data, 
                     for: [
                        Instruction(instruction: "mul", params: 2)
                     ])
    return execute(instructions)
}

func part2() -> Any {
    let instructions = parse(data,
                     for: [
                      Instruction(instruction: "mul", params: 2),
                      Instruction(instruction: "do", params: 0),
                      Instruction(instruction: "don't", params: 0)
                     ])
    return execute(instructions)
}

Benchmarked:

$ swift run -c release AdventOfCode 3 --benchmark
Building for production...
[6/6] Linking AdventOfCode
Build of product 'AdventOfCode' complete! (2.55s)
Executing Advent of Code challenge 3...
Part 1: 188116424
Part 2: 104245808
Part 1 took 0.00304425 seconds, part 2 took 0.004164459 seconds.