Use bitmask to save space on Day 3

This commit is contained in:
2026-02-17 19:54:16 -05:00
parent f4ad14a34a
commit fafa2b6550

View File

@@ -70,36 +70,28 @@ sum_rucksack :: proc(sack: string) -> int {
}
find_common_item :: proc(sacks: []string) -> int {
size := 52 * len(sacks)
fmt.printf("Sacks: %d; Size: %d\n", len(sacks), size)
size := 52
counter := make([]int, size) // Dynamic array initialized to all 0
defer delete(counter) // Clean up memory when it goes out of scope
counter := make([]int, size)
defer delete(counter)
for idx in 0..<size {
counter[idx] = 0
// Compute the max value for a counter
max_counter := 0
idx : u32 = 0
for _ in 0..<len(sacks) {
max_counter = max_counter & (1 << idx)
idx += 1
}
for str, offset in sacks {
fmt.printf("Sack: %s\n", str)
for chr, _ in str {
// Check every item in every rucksack
for sack, offset_ in sacks {
offset := u32(offset_)
for chr, _ in sack {
prio := priority(chr) - 1
fmt.printf("Found char: %c (%d)\n", chr, prio + 1)
counter[(len(sacks) * prio) + offset] = 1
}
}
fmt.println(counter)
for prio in 0..<52 {
fmt.printf("Checking prio %d\n", prio)
matched := true
for offset in 0..<len(sacks) {
idx := (len(sacks) * prio) + offset
fmt.printf("Checking index %d\n", idx)
matched = matched && (counter[idx] == 1)
}
if matched {
return prio + 1
counter[prio] = counter[prio] & (1 << offset)
// If we hit the max value, we can just quit without checking anything else - this is because per the problem there should only be one item that appears in all three rucksacks
if counter[prio] == max_counter {
return prio + 1
}
}
}
return 0
@@ -430,7 +422,6 @@ main :: proc() {
upper_bound := idx + step
offset := min(len(input), upper_bound)
prio := find_common_item(input[idx:offset])
fmt.printf("Priority: %d\n", prio)
total += prio
idx = upper_bound
}