Optimize day 3

Avoid instantiating module and backtracking, instead use regex for
filtering. Much faster. Since we are not matching brackets, but rather
only care about the last instance, the limitations of regex don't apply.
This commit is contained in:
2024-12-07 10:42:38 +01:00
parent c871a9ea24
commit edb0767201
2 changed files with 6 additions and 30 deletions

View File

@@ -3,22 +3,17 @@ variable "input" {
}
locals {
filtered = replace(var.input, "/(?s)don't\\(\\).*?do\\(\\)/", "")
filtered2 = replace(local.filtered, "/(?s)don't\\(\\).*/", "")
muls = regexall("mul\\((\\d+),(\\d+)\\)", var.input)
ops = regexall("(don't\\(\\)|do\\(\\)|mul\\((\\d+),(\\d+)\\))", var.input)
}
module "should_execute" {
count = length(local.ops)
source = "./should_execute"
index = count.index
ops = local.ops
filtered_muls = regexall("mul\\((\\d+),(\\d+)\\)", local.filtered2)
}
output "part1" {
value = sum([for mul in local.muls : parseint(mul[1], 10) * parseint(mul[0], 10)])
value = sum([for mul in local.muls : tonumber(mul[1]) * tonumber(mul[0])])
}
output "part2" {
value = sum(module.should_execute[*].value)
value = sum([for mul in local.filtered_muls : tonumber(mul[1]) * tonumber(mul[0])])
}

View File

@@ -1,19 +0,0 @@
variable "ops" {
type = list(list(string))
}
variable "index" {
type = number
}
locals {
is_mul = startswith(var.ops[var.index][0], "mul")
subslice = reverse(slice(var.ops[*][0], 0, var.index))
do_pos = try(index(local.subslice, "do()"), var.index)
dont_pos = try(index(local.subslice, "don't()"), var.index + 1)
}
output "value" {
value = (local.is_mul && local.do_pos < local.dont_pos) ? (parseint(var.ops[var.index][1], 10) * parseint(var.ops[var.index][2], 10)) : 0
}