From edb07672010ad6911ad783d0a8ee0678011b520a Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Sat, 7 Dec 2024 10:42:38 +0100 Subject: [PATCH] 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. --- 2024/bonus/day03/main.tf | 17 ++++++----------- 2024/bonus/day03/should_execute/main.tf | 19 ------------------- 2 files changed, 6 insertions(+), 30 deletions(-) delete mode 100644 2024/bonus/day03/should_execute/main.tf diff --git a/2024/bonus/day03/main.tf b/2024/bonus/day03/main.tf index 180df28..795c19f 100644 --- a/2024/bonus/day03/main.tf +++ b/2024/bonus/day03/main.tf @@ -3,22 +3,17 @@ variable "input" { } locals { - muls = regexall("mul\\((\\d+),(\\d+)\\)", var.input) - ops = regexall("(don't\\(\\)|do\\(\\)|mul\\((\\d+),(\\d+)\\))", var.input) -} + filtered = replace(var.input, "/(?s)don't\\(\\).*?do\\(\\)/", "") + filtered2 = replace(local.filtered, "/(?s)don't\\(\\).*/", "") -module "should_execute" { - count = length(local.ops) - source = "./should_execute" - - index = count.index - ops = local.ops + muls = regexall("mul\\((\\d+),(\\d+)\\)", var.input) + 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])]) } diff --git a/2024/bonus/day03/should_execute/main.tf b/2024/bonus/day03/should_execute/main.tf deleted file mode 100644 index 41ac777..0000000 --- a/2024/bonus/day03/should_execute/main.tf +++ /dev/null @@ -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 -}