-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
136 lines (121 loc) · 2.13 KB
/
main.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"io"
"strings"
aoc "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader) int {
del := aoc.NewDelimiter(aoc.ReaderToString(input), ",")
res := 0
for _, s := range del.GetStrings() {
res += hash(s)
}
return res
}
func hash(s string) int {
res := 0
for _, c := range s {
res += int(c)
res *= 17
res %= 256
}
return res
}
type Box struct {
tail *Lense
labels map[string]*Lense
}
type Lense struct {
label string
size int
next *Lense
previous *Lense
}
func fs2(input io.Reader) int {
del := aoc.NewDelimiter(aoc.ReaderToString(input), ",")
boxes := make([]*Box, 256)
for i := 0; i < 256; i++ {
boxes[i] = &Box{
labels: make(map[string]*Lense),
}
}
for _, s := range del.GetStrings() {
handleOperation(boxes, s)
}
res := 0
for idx, box := range boxes {
res += getPower(idx+1, box)
}
return res
}
func handleOperation(boxes []*Box, s string) {
if strings.Contains(s, "-") {
label := s[:len(s)-1]
idx := hash(label)
box := boxes[idx]
if lense, exists := box.labels[label]; exists {
delete(box.labels, label)
tail := box.tail
if tail.label == lense.label {
if tail.next != nil {
box.tail = tail.next
box.tail.previous = nil
} else {
box.tail = nil
}
return
}
next := lense.next
if lense.previous != nil {
lense.previous.next = next
if next != nil {
next.previous = lense.previous
}
}
}
} else {
del := aoc.NewDelimiter(s, "=")
label := del.GetString(0)
idx := hash(label)
size := del.GetInt(1)
box := boxes[idx]
if lense, exists := box.labels[label]; exists {
lense.size = size
} else {
tail := box.tail
l := &Lense{
label: label,
size: size,
}
if tail == nil {
box.tail = l
} else {
tail.previous = l
l.next = tail
box.tail = l
}
box.labels[label] = l
}
}
}
func getPower(idx int, box *Box) int {
// Finding head
cur := box.tail
if cur == nil {
return 0
}
for {
if cur.next == nil {
break
}
cur = cur.next
}
res := 0
i := 1
for cur != nil {
res += cur.size * i * idx
i++
cur = cur.previous
}
return res
}