Skip to content

Commit edb0767

Browse files
committed
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.
1 parent c871a9e commit edb0767

File tree

2 files changed

+6
-30
lines changed

2 files changed

+6
-30
lines changed

2024/bonus/day03/main.tf

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,17 @@ variable "input" {
33
}
44

55
locals {
6-
muls = regexall("mul\\((\\d+),(\\d+)\\)", var.input)
7-
ops = regexall("(don't\\(\\)|do\\(\\)|mul\\((\\d+),(\\d+)\\))", var.input)
8-
}
9-
10-
module "should_execute" {
11-
count = length(local.ops)
12-
source = "./should_execute"
6+
filtered = replace(var.input, "/(?s)don't\\(\\).*?do\\(\\)/", "")
7+
filtered2 = replace(local.filtered, "/(?s)don't\\(\\).*/", "")
138

14-
index = count.index
15-
ops = local.ops
9+
muls = regexall("mul\\((\\d+),(\\d+)\\)", var.input)
10+
filtered_muls = regexall("mul\\((\\d+),(\\d+)\\)", local.filtered2)
1611
}
1712

1813
output "part1" {
19-
value = sum([for mul in local.muls : parseint(mul[1], 10) * parseint(mul[0], 10)])
14+
value = sum([for mul in local.muls : tonumber(mul[1]) * tonumber(mul[0])])
2015
}
2116

2217
output "part2" {
23-
value = sum(module.should_execute[*].value)
18+
value = sum([for mul in local.filtered_muls : tonumber(mul[1]) * tonumber(mul[0])])
2419
}

2024/bonus/day03/should_execute/main.tf

Lines changed: 0 additions & 19 deletions
This file was deleted.

0 commit comments

Comments
 (0)