-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03.go
84 lines (61 loc) · 1.81 KB
/
day03.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
package day03
import (
"strings"
)
func parseRucksackCompartments(input string) (parsedRucksack [][]string) {
for _, rucksack := range strings.Split(input, "\n") {
compartmentDelimiter := len(rucksack) / 2
firstCompartment := rucksack[0:compartmentDelimiter]
secondCompartment := rucksack[compartmentDelimiter:]
parsedRucksack = append(parsedRucksack, []string{firstCompartment, secondCompartment})
}
return
}
func getItemPriority(item rune) int {
if item >= 'a' && item <= 'z' {
return int(item - 'a' + 1)
} else {
return int(item - 'A' + 27)
}
}
func part1(input string) (prioritySum int) {
rucksacks := parseRucksackCompartments(input)
for _, rucksack := range rucksacks {
firstCompartmentItemsMap := make(map[rune]bool)
for _, item := range rucksack[0] {
firstCompartmentItemsMap[item] = true
}
secondCompartmentItemsMap := make(map[rune]bool)
for _, item := range rucksack[1] {
if firstCompartmentItemsMap[item] && !secondCompartmentItemsMap[item] {
prioritySum += getItemPriority(item)
}
secondCompartmentItemsMap[item] = true
}
}
return
}
func part2(input string) (prioritySum int) {
rucksacks := strings.Split(input, "\n")
for cursor := 0; cursor < len(rucksacks); cursor += 3 {
elvesGroup := rucksacks[cursor : cursor+3]
firstElfItems := make(map[rune]bool)
for _, item := range elvesGroup[0] {
firstElfItems[item] = true
}
secondAndFirstElfItems := make(map[rune]bool)
for _, item := range elvesGroup[1] {
if firstElfItems[item] && !secondAndFirstElfItems[item] {
secondAndFirstElfItems[item] = true
}
}
commonToAllItems := make(map[rune]bool)
for _, item := range elvesGroup[2] {
if secondAndFirstElfItems[item] && !commonToAllItems[item] {
prioritySum += getItemPriority(item)
}
commonToAllItems[item] = true
}
}
return
}