-
Notifications
You must be signed in to change notification settings - Fork 0
/
15p2.go
91 lines (78 loc) · 1.74 KB
/
15p2.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
package main
import (
"fmt"
"strconv"
"strings"
"aoc2023/utils"
)
type step struct {
label string
labelHash int
operator rune
value int
}
func D15P2() {
lines := utils.ReadLines("inputs/15.txt")
steps := parseSteps(lines[0])
lensBoxes := map[int][]step{}
for _, step := range steps {
currentBox := lensBoxes[step.labelHash]
if step.operator == '=' {
boxContainsStep := false
for i, lens := range currentBox {
if lens.label == step.label {
boxContainsStep = true
currentBox[i] = step
break
}
}
if !boxContainsStep {
currentBox = append(currentBox, step)
lensBoxes[step.labelHash] = currentBox
continue
}
}
if step.operator == '-' {
for i, lens := range currentBox {
if lens.label == step.label {
currentBox = append(currentBox[:i], currentBox[i+1:]...)
lensBoxes[step.labelHash] = currentBox
break
}
}
}
continue
}
focussingPower := 0
for key, value := range lensBoxes {
for i, step := range value {
focussingPower += (key + 1) * (i + 1) * step.value
}
}
fmt.Printf("The focussing power of the lens array is %d\n", focussingPower)
}
func parseSteps(line string) []step {
steps := []step{}
stepStrings := strings.Split(line, ",")
for _, stepString := range stepStrings {
step := step{}
parsingLabel := true
for i := 0; i < len(stepString) && parsingLabel; i++ {
char := rune(stepString[i])
switch char {
case '=':
step.operator = char
step.value, _ = strconv.Atoi(stepString[i+1:])
parsingLabel = false
case '-':
step.operator = char
parsingLabel = false
default:
step.label += string(char)
}
}
step.labelHash = getStringHashValue(step.label)
steps = append(steps, step)
}
return steps
}