aoc2023/day-15/two.go

58 lines
1.1 KiB
Go
Raw Normal View History

2023-12-15 17:19:33 +00:00
package main
import (
"strings"
"github.com/elliotchance/orderedmap/v2"
)
var boxes = map[int]*orderedmap.OrderedMap[string, int]{}
// add places a lense into an ordered box
func add(id int, label string, focalLength int) {
boxes[id].Set(label, focalLength)
}
// remove takes a lense out of an ordered box
func remove(id int, label string) {
boxes[id].Delete(strings.TrimRight(label, "-"))
}
// two returns the sum of all lense configurations
func two(lines []string) int {
hash := newHasher()
for _, lense := range lenses {
label, focalLength := func() (string, int) {
x := strings.Split(lense, "=")
if len(x) == 2 {
return x[0], mustConv(x[1])
}
return strings.TrimRight(x[0], "-"), 0
}()
boxId := hash.run(label)
_, ok := boxes[boxId]
if !ok {
m := orderedmap.NewOrderedMap[string, int]()
boxes[boxId] = m
}
if strings.Contains(lense, "=") {
add(boxId, label, focalLength)
} else {
remove(boxId, label)
}
}
sum := 0
for id, box := range boxes {
for index, lense := range box.Keys() {
focalLength, _ := box.Get(lense)
sum += (id + 1) * (index + 1) * focalLength
}
}
return sum
}