AOC2022/day3/day3.go
2022-12-03 19:41:59 +01:00

69 lines
1.6 KiB
Go

package main
import (
"AOC2022/helper"
"fmt"
"os"
)
func main() {
args := os.Args[1:]
rucksacks := helper.ReadTextFile(args[0])
part1(rucksacks)
part2(rucksacks)
}
func part2(rucksacks []string) {
sum := int32(0)
for i := 0; i < len(rucksacks); i += 3 {
repeatedItems := findRepeatedItems(rucksackStringToItemprioList(rucksacks[i]), rucksackStringToItemprioList(rucksacks[i+1]))
repeatedItems = findRepeatedItems(repeatedItems, rucksackStringToItemprioList(rucksacks[i+2]))
for _, repeatedItem := range repeatedItems {
sum += repeatedItem
}
}
fmt.Println(sum)
}
func part1(rucksacks []string) {
sum := int32(0)
for _, rucksack := range rucksacks {
repeatedElemnts := findRepeatedItems(rucksackStringToItemprioList(rucksack[:len(rucksack)/2]), rucksackStringToItemprioList(rucksack[len(rucksack)/2:]))
for _, repeatedElemnt := range repeatedElemnts {
sum += repeatedElemnt
}
}
fmt.Println(sum)
}
func findRepeatedItems(itemgroup1, itemgroup2 []int32) []int32 {
elementsCompartment1 := map[int32]bool{}
repeatedElemnts := map[int32]bool{}
for _, item := range itemgroup1 {
elementsCompartment1[item] = true
}
for _, item := range itemgroup2 {
if elementsCompartment1[item] {
repeatedElemnts[item] = true
}
}
v := make([]int32, 0, len(repeatedElemnts))
for key, _ := range repeatedElemnts {
v = append(v, key)
}
return v
}
func rucksackStringToItemprioList(rucksack string) (itemprioList []int32) {
for _, item := range rucksack {
if item > 90 {
itemprioList = append(itemprioList, item-96)
} else {
itemprioList = append(itemprioList, item-38)
}
}
return
}