github.com/vpayno/adventofcode-2022-golang-workspace@v0.0.0-20230605190011-dbafed5593de/internal/day03/init.go (about) 1 // Package day03 is the module with the cli logic for the cmd application. 2 package day03 3 4 import ( 5 "errors" 6 "fmt" 7 "strings" 8 "unicode" 9 ) 10 11 // Config holds the application's configuration. 12 type Config struct { 13 appName string 14 inputFileName string 15 } 16 17 // Rucksack holds an Elf's items. 18 type rucksack struct { 19 items string 20 } 21 22 func (r *rucksack) addItems(items string) error { 23 if len(items)%2 != 0 { 24 return fmt.Errorf("items list isn't evenly divisible (len=%d)", len(items)) 25 } 26 27 r.items = items 28 29 return nil 30 } 31 32 func (r *rucksack) getCollection(num int) string { 33 34 if num == 1 { 35 return r.items[0 : len(r.items)/2] 36 } 37 38 return r.items[len(r.items)/2:] 39 } 40 41 // lot's of room or optimizations 42 func (r *rucksack) getSharedItem() (rune, error) { 43 collection1 := r.getCollection(1) 44 collection2 := r.getCollection(2) 45 46 for _, char := range collection1 { 47 if strings.ContainsRune(collection2, char) { 48 return char, nil 49 } 50 } 51 52 return rune(0), errors.New("rucksack compartments doesn't have a shared item") 53 } 54 55 func (r *rucksack) getSharedPriority() (int, error) { 56 shared, err := r.getSharedItem() 57 if err != nil { 58 return 0, err 59 } 60 61 return getPriority(shared), nil 62 } 63 64 type rucksacks []rucksack 65 66 // Setup creates the applications configuration object. 67 func Setup(appName string) Config { 68 69 conf := Config{ 70 appName: appName, 71 inputFileName: "data/" + appName + "/" + appName + "-input.txt", 72 } 73 74 return conf 75 } 76 77 func getPriority(item rune) int { 78 if unicode.IsLower(item) { 79 return int(item) - 96 80 } 81 82 return int(item) - 38 83 }