mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
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:
@@ -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])])
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user