Skip to content

Commit 612c4d1

Browse files
committed
Implement efficient algorithm in TF
1 parent 2beccdd commit 612c4d1

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

2024/bonus/day11/main.tf

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@ variable "input" {
44

55
locals {
66
nums = [for s in split(" ", chomp(var.input)) : tonumber(s)]
7+
8+
grouped = { for num in local.nums : num => 1... }
9+
total = { for k, v in local.grouped : k => sum(v) }
710
}
811

912
module "step1" {
1013
source = "./step"
1114

12-
prev = local.nums
15+
prev = local.total
1316
}
1417

1518
module "step2" {
@@ -157,5 +160,5 @@ module "step25" {
157160
}
158161

159162
output "part1" {
160-
value = length(flatten(module.step25.next))
163+
value = sum(values(module.step25.next))
161164
}

2024/bonus/day11/step/main.tf

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
11
variable "prev" {
2-
type = list(number)
2+
type = map(number)
3+
}
4+
5+
module "transform" {
6+
source = "../transform"
7+
for_each = var.prev
8+
9+
num = each.key
310
}
411

512
locals {
6-
values = [
7-
for num in var.prev : num == 0 ? [1]
8-
: length(tostring(num)) % 2 == 0
9-
? [tonumber(substr(tostring(num), 0, length(tostring(num)) / 2)), tonumber(substr(tostring(num), length(tostring(num)) / 2, 10))]
10-
: [num * 2024]
11-
]
13+
by_value = flatten([
14+
for key, value in module.transform :
15+
[for result in value.result : { num = result, count = var.prev[key] }]
16+
])
17+
18+
grouped = { for kv in local.by_value : kv.num => kv.count... }
1219
}
1320

1421
# module "transform" {
@@ -23,5 +30,5 @@ locals {
2330
# }
2431

2532
output "next" {
26-
value = flatten(local.values)
33+
value = { for num, groups in local.grouped : num => sum(groups) }
2734
}

0 commit comments

Comments
 (0)