generated from devries/aoc_template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.go
89 lines (71 loc) · 1.46 KB
/
solution.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package day15p2
import (
"io"
"strconv"
"strings"
"aoc/utils"
)
func Solve(r io.Reader) any {
lines := utils.ReadLines(r)
steps := strings.Split(lines[0], ",")
boxes := make(map[byte][]Lens)
for _, s := range steps {
if strings.Contains(s, "=") {
parts := strings.Split(s, "=")
fl, err := strconv.Atoi(parts[1])
utils.Check(err, "unable to convert %s to integer", parts[1])
h := elfHash(parts[0])
lenses := boxes[h]
found := false
for i, l := range lenses {
if l.Label == parts[0] {
found = true
l.FocalLength = fl
lenses[i] = l
break
}
}
if !found {
newlenses := make([]Lens, len(lenses)+1)
copy(newlenses, lenses)
newlenses[len(lenses)] = Lens{parts[0], fl}
boxes[h] = newlenses
}
} else {
label, _ := strings.CutSuffix(s, "-")
h := elfHash(label)
lenses := boxes[h]
newlenses := make([]Lens, 0, len(lenses))
for _, l := range lenses {
if l.Label != label {
newlenses = append(newlenses, l)
}
}
boxes[h] = newlenses
}
}
// Find focusing power
var sum uint64
for i := 0; i < 256; i++ {
lenses := boxes[byte(i)]
if len(lenses) != 0 {
for j, l := range lenses {
boxpower := (uint64(i) + 1) * uint64((j+1)*l.FocalLength)
sum += boxpower
}
}
}
return sum
}
func elfHash(s string) byte {
var res byte
for _, r := range s {
res += byte(r)
res *= 17
}
return res
}
type Lens struct {
Label string
FocalLength int
}