Use bitmask to save space on Day 3
This commit is contained in:
@@ -70,36 +70,28 @@ sum_rucksack :: proc(sack: string) -> int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
find_common_item :: proc(sacks: []string) -> int {
|
find_common_item :: proc(sacks: []string) -> int {
|
||||||
size := 52 * len(sacks)
|
size := 52
|
||||||
fmt.printf("Sacks: %d; Size: %d\n", len(sacks), size)
|
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)
|
// Compute the max value for a counter
|
||||||
defer delete(counter)
|
max_counter := 0
|
||||||
|
idx : u32 = 0
|
||||||
for idx in 0..<size {
|
for _ in 0..<len(sacks) {
|
||||||
counter[idx] = 0
|
max_counter = max_counter & (1 << idx)
|
||||||
|
idx += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
for str, offset in sacks {
|
// Check every item in every rucksack
|
||||||
fmt.printf("Sack: %s\n", str)
|
for sack, offset_ in sacks {
|
||||||
for chr, _ in str {
|
offset := u32(offset_)
|
||||||
|
for chr, _ in sack {
|
||||||
prio := priority(chr) - 1
|
prio := priority(chr) - 1
|
||||||
fmt.printf("Found char: %c (%d)\n", chr, prio + 1)
|
counter[prio] = counter[prio] & (1 << offset)
|
||||||
counter[(len(sacks) * prio) + offset] = 1
|
// 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
|
||||||
|
}
|
||||||
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
@@ -430,7 +422,6 @@ main :: proc() {
|
|||||||
upper_bound := idx + step
|
upper_bound := idx + step
|
||||||
offset := min(len(input), upper_bound)
|
offset := min(len(input), upper_bound)
|
||||||
prio := find_common_item(input[idx:offset])
|
prio := find_common_item(input[idx:offset])
|
||||||
fmt.printf("Priority: %d\n", prio)
|
|
||||||
total += prio
|
total += prio
|
||||||
idx = upper_bound
|
idx = upper_bound
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user