github.com/vpayno/adventofcode-2022-golang-workspace@v0.0.0-20230605190011-dbafed5593de/internal/day03/app.go (about) 1 // Package day03 is the module with the cli logic for the application. 2 package day03 3 4 import ( 5 "bufio" 6 "fmt" 7 8 "github.com/vpayno/adventofcode-2022-golang-workspace/internal/aocshared" 9 ) 10 11 // Run is called my the gain function. It's basically the main function of the app. 12 func Run(conf Config) error { 13 file, err := aocshared.GetFile(conf.inputFileName) 14 if err != nil { 15 return err 16 } 17 18 scanner := aocshared.GetScanner(file) 19 20 data, err := loadData(scanner) 21 if err != nil { 22 return err 23 } 24 25 prioritySum, err := getPrioritySum(data) 26 if err != nil { 27 return err 28 } 29 30 aocshared.ShowResult(prioritySum) 31 32 groupPrioritySum, err := getGroupPrioritySum(data) 33 if err != nil { 34 return err 35 } 36 37 aocshared.ShowResult(groupPrioritySum) 38 39 return nil 40 } 41 42 func loadData(file *bufio.Scanner) (rucksacks, error) { 43 data := rucksacks{} 44 45 for file.Scan() { 46 line := file.Text() 47 48 if line == "" { 49 continue 50 } 51 52 r := rucksack{} 53 err := r.addItems(line) 54 if err != nil { 55 return data, err 56 } 57 58 data = append(data, r) 59 } 60 61 return data, nil 62 } 63 64 func getPrioritySum(data rucksacks) (int, error) { 65 var result int 66 67 for _, r := range data { 68 priority, err := r.getSharedPriority() 69 if err != nil { 70 return 0, err 71 } 72 73 result += priority 74 } 75 76 return result, nil 77 } 78 79 func getGroupPrioritySum(data rucksacks) (int, error) { 80 var groupSum int 81 group := []string{} 82 sacks := [][]string{} 83 84 if len(data) == 0 { 85 err := fmt.Errorf("rucksack list is empty: %v", data) 86 return 0, err 87 } 88 89 if len(data)%3 != 0 { 90 err := fmt.Errorf("rucksack list length, %d, isn't evenly divisible by 3", len(data)) 91 return 0, err 92 } 93 94 for i, r := range data { 95 if i%3 == 0 && i > 0 { 96 sacks = append(sacks, group) 97 group = []string{} 98 } 99 100 group = append(group, r.items) 101 } 102 103 sacks = append(sacks, group) 104 105 for _, group := range sacks { 106 // not handling the case where the number of rucksacks isn't evenly divisibleby 3 107 g1 := aocshared.SetFromSlice(aocshared.SplitString(group[0])) 108 g2 := aocshared.SetFromSlice(aocshared.SplitString(group[1])) 109 g3 := aocshared.SetFromSlice(aocshared.SplitString(group[2])) 110 111 c1 := aocshared.SetFromSlice(aocshared.SetIntersect(g1, g2)) 112 c2 := aocshared.SetFromSlice(aocshared.SetIntersect(g1, g3)) 113 c3 := aocshared.SetFromSlice(aocshared.SetIntersect(g2, g3)) 114 115 c1 = aocshared.SetFromSlice(aocshared.SetIntersect(c1, c2)) 116 c1 = aocshared.SetFromSlice(aocshared.SetIntersect(c1, c3)) 117 118 for item := range c1 { 119 priority := getPriority(item) 120 groupSum += priority 121 } 122 } 123 124 return groupSum, nil 125 }