commit 1fd84fa16914c0d363e9c86eb3c63c368b3e957b
parent 25b8bbe6203fa094f3e803a69779e4f87db9d6a3
Author: bsandro <email@bsandro.tech>
Date: Sat, 3 Dec 2022 06:40:09 +0000
Day 03 part 2
Diffstat:
M | day03/main.go | | | 58 | +++++++++++++++++++++++++++++++++++++++++++--------------- |
1 file changed, 43 insertions(+), 15 deletions(-)
diff --git a/day03/main.go b/day03/main.go
@@ -25,33 +25,45 @@ func day03(input_file string) {
}
defer input.Close()
scanner := bufio.NewScanner(input)
- var sum int32 = 0
+ var sum1 int32 = 0
+ var sum2 int32 = 0
+ var group []string
for scanner.Scan() {
- same := findSame(scanner.Text())
- // unicode rune to fantasy scoring
- if same >= 97 { // lowercase
- same -= 96
- } else if same >= 65 { // uppercase
- same -= 38
- } else {
- log.Fatal("Invalid rune")
+ rucksack := scanner.Text()
+ item1 := compareCompartments(rucksack)
+ sum1 += getItemScore(item1)
+ group = append(group, rucksack)
+ if len(group) == 3 {
+ item2 := compareRucksacks(group)
+ sum2 += getItemScore(item2)
+ group = nil
}
- fmt.Printf("%v\n", same)
- sum += same
}
- fmt.Println("Part 1:", sum)
if err = scanner.Err(); err != nil {
log.Fatal(err)
}
+
+ fmt.Println("Part 1:", sum1)
+ fmt.Println("Part 2:", sum2)
+}
+
+func getItemScore(item int32) int32 {
+ // unicode rune to fantasy scoring
+ if item >= 97 { // lowercase
+ return item - 96
+ } else if item >= 65 { // uppercase
+ return item - 38
+ }
+ return 0
}
-func findSame(in string) int32 {
+func compareCompartments(in string) int32 {
strLen := len(in)
- if strLen % 2 != 0 {
+ if strLen%2 != 0 {
log.Fatal("invalid input string")
}
- comp1 := in[0:strLen/2]
+ comp1 := in[0 : strLen/2]
comp2 := in[strLen/2:]
// only 1 misplaced item per rucksack
@@ -65,3 +77,19 @@ func findSame(in string) int32 {
return 0
}
+
+func compareRucksacks(group []string) int32 {
+ if len(group) != 3 {
+ log.Fatal("Group size has to be 3")
+ }
+ for _, r1 := range group[0] {
+ for _, r2 := range group[1] {
+ for _, r3 := range group[2] {
+ if r1 == r2 && r2 == r3 {
+ return r1
+ }
+ }
+ }
+ }
+ return 0
+}