mirror of
https://github.com/onyx-and-iris/aoc2023.git
synced 2024-09-27 18:26:59 +01:00
58 lines
1.1 KiB
Go
58 lines
1.1 KiB
Go
|
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
|
||
|
}
|