diff --git a/day03/common/rucksack.go b/day03/common/rucksack.go new file mode 100644 index 0000000..08f4ec4 --- /dev/null +++ b/day03/common/rucksack.go @@ -0,0 +1,57 @@ +package common + +import ( + "bufio" +) + +type Compartment struct { + items []int +} + +func (compartment *Compartment) AddItem(itemName byte) { + if itemName < 'a' { + compartment.items = append(compartment.items, int(itemName - 'A' + 27)) + } else { + compartment.items = append(compartment.items, int(itemName - 'a' + 1)) + } +} + +func (compartment Compartment) GetItems() []int { + return compartment.items +} + +func (compartment Compartment) ContainsItem(item int) bool { + for _, cItem := range compartment.items { + if item == cItem { + return true + } + } + return false +} + +type Rucksack struct { + compartments [2]Compartment +} + +func (rucksack Rucksack) GetCompartment(id int) Compartment { + return rucksack.compartments[id-1] +} + +func Parse(scanner bufio.Scanner) []Rucksack { + rucksacks := []Rucksack{} + + for scanner.Scan() { + currentRucksack := Rucksack{} + line := scanner.Text() + compartmentLength := len(line) / 2 + for i := 0; i < compartmentLength; i++ { + currentRucksack.compartments[0].AddItem(line[i]) + } + for i := 0; i < compartmentLength; i++ { + currentRucksack.compartments[1].AddItem(line[compartmentLength+i]) + } + rucksacks = append(rucksacks, currentRucksack) + } + + return rucksacks +} diff --git a/day03/ex1/main.go b/day03/ex1/main.go new file mode 100644 index 0000000..00b82c3 --- /dev/null +++ b/day03/ex1/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "aoc2022/day03/common" +) + +func main() { + rucksacks := common.Parse(*bufio.NewScanner(os.Stdin)) + sum := 0 + + for _, rucksack := range rucksacks { + for _, item := range rucksack.GetCompartment(1).GetItems() { + if rucksack.GetCompartment(2).ContainsItem(item) { + sum += item + break + } + } + } + + fmt.Println(sum) +} diff --git a/day03/ex2/main.go b/day03/ex2/main.go new file mode 100644 index 0000000..32552b3 --- /dev/null +++ b/day03/ex2/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "aoc2022/day03/common" +) + +func main() { + rucksacks := common.Parse(*bufio.NewScanner(os.Stdin)) + sum := 0 + + for i := 0; i < len(rucksacks); i+=3 { + rucksack := rucksacks[i] + commonItems := append(rucksack.GetCompartment(1).GetItems(), rucksack.GetCompartment(2).GetItems()...) + for j := 1; j <= 2; j++ { + for k := 0; k < len(commonItems); k++ { + item := commonItems[k] + if !rucksacks[i+j].GetCompartment(1).ContainsItem(item) && !rucksacks[i+j].GetCompartment(2).ContainsItem(item) { + commonItems = append(commonItems[:k], commonItems[k+1:]...) + k-- + } + } + } + sum += commonItems[0] + } + + fmt.Println(sum) +}