❌ Day 03 - Mull it over Link to heading

We have a long String like this:

xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))

Which is a dump from the memory of a corrupted computer, but it still contains some valid instructions. We have to filter out the intact instructions and execute them.

Part One Link to heading

For part one, we only need to check for one instruction: mul(x, y), which, as you probably guessed, is a multiplication instruction. To get the result for the part, we have to find all mul instructions, execute them, and sum the result.

To parse out the muls, I whooped out the good old regexr and came up with this bad boy:

mul\([0-9]+,[0-9]+\)

And made this little piece of beatiful kotlin code to execute the found instructions:

fun parseMultiplication(str: String): Int = 
  str.trim { !it.isDigit() && it != ',' }
    .split(",")
    .map { it.toInt() }
    .fold(1) { acc, num -> acc * num}

Then I combined both and finished part one:

input.let {
  Regex("""mul\([0-9]+,[0-9]+\)""").findAll(it)
}.sumOf {
  parseMultiplication(it.value)
}

And for the given test input it returned 161, which is correct, so let’s carry on!

Part Two Link to heading

Now for Part two we have two new instructions, do() and don't(), which enable and disable the multiplication instructions. Basically, if we find a mul and the last other instruction was don't(), do not count the value. The code starts with muls enabled.

For this task, we got a new Puzzle input, so lets take a look at it:

xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))

The first mul are executed, but the second and fourth are not because of the don't() before them. After the fourth, we find a do() inside of the undo() so we count the last one too (The other ones are invalidly structured so we can ignore them).

This required a bit of modification to my Regex to also parse the new instructions, and a pattern match to check which instruction should be executed:

var enabled = true
input.let {
  Regex("""(mul\([0-9]+,[0-9]+\)|do[n't]*\(\))""").findAll(it)
}.sumOf {
  when {
    it.value.startsWith("mul") -> if (enabled) parseMultiplication(it.value) else 0
    it.value == "don't()" -> { enabled = false; 0}
    it.value == "do()" -> { enabled = true; 0 }
    else -> 0
  }
}

Which returns 48 on the test input and secures the second star for today!