-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday03_rucksack.go
116 lines (97 loc) · 2.5 KB
/
day03_rucksack.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
package main
import (
"fmt"
"os"
"strings"
)
type rucksack struct {
comparment1 string
comparment2 string
}
func readRucksackFile(filePath string) []string {
input, _ := os.ReadFile(filePath)
return strings.Split(strings.TrimSpace(string(input)), "\n")
}
func scoreCommonItemInEachRucksack(rucksacks []string) int {
// parse each rucksack component
allRucksacks := make([]rucksack, 0)
for _, line := range rucksacks {
rucksack := rucksack{comparment1: line[:len(line)/2], comparment2: line[len(line)/2:]}
allRucksacks = append(allRucksacks, rucksack)
}
// score common elements
totalScore := 0
for _, rucksack := range allRucksacks {
comparment1Set := make(map[int]void)
for _, item := range rucksack.comparment1 {
comparment1Set[int(item)] = member
}
comparment2Set := make(map[int]void)
for _, item := range rucksack.comparment2 {
comparment2Set[int(item)] = member
}
for k := range comparment1Set {
if _, ok := comparment2Set[k]; ok {
if k > 90 {
totalScore += (k - 96)
} else {
totalScore += (k - 38)
}
}
}
}
return totalScore
}
func scoreGroupsUniqueItems(rucksacks []string) int {
totalScore := 0
// elves hang out in triples
for i := 0; i < len(rucksacks)/3; i++ {
elf1RuckSack := rucksacks[i*3]
elf1Set := make(map[int]void)
for _, item := range elf1RuckSack {
elf1Set[int(item)] = member
}
elf2RuckSack := rucksacks[(i*3)+1]
elf2Set := make(map[int]void)
for _, item := range elf2RuckSack {
elf2Set[int(item)] = member
}
elf3RuckSack := rucksacks[(i*3)+2]
elf3Set := make(map[int]void)
for _, item := range elf3RuckSack {
elf3Set[int(item)] = member
}
for k := range elf1Set {
if _, ok := elf2Set[k]; ok {
if _, ok := elf3Set[k]; ok {
if k > 90 {
totalScore += (k - 96)
} else {
totalScore += (k - 38)
}
}
}
}
}
return totalScore
}
func day03() {
// Part 1
rucksacks := readRucksackFile("2022/data/day03_sample.txt")
result := scoreCommonItemInEachRucksack(rucksacks)
if result != 157 {
panic("Part 1 example is failing")
}
rucksacks = readRucksackFile("2022/data/day03_input.txt")
result = scoreCommonItemInEachRucksack(rucksacks)
fmt.Println("Part 1:", result)
// Part 2
rucksacks = readRucksackFile("2022/data/day03_sample.txt")
result = scoreGroupsUniqueItems(rucksacks)
if result != 70 {
panic("Part 2 example is failing")
}
rucksacks = readRucksackFile("2022/data/day03_input.txt")
result = scoreGroupsUniqueItems(rucksacks)
fmt.Println("Part 2:", result)
}