github.com/vpayno/adventofcode-2022-golang-workspace@v0.0.0-20230605190011-dbafed5593de/internal/day04/init.go (about) 1 // Package day04 is the module with the cli logic for the cmd application. 2 package day04 3 4 import ( 5 "fmt" 6 "strconv" 7 "strings" 8 ) 9 10 // Config holds the application's configuration. 11 type Config struct { 12 appName string 13 inputFileName string 14 } 15 16 // Section stores the start and end range of an Elf's section. 17 type section struct { 18 start int 19 end int 20 } 21 22 func (s *section) addRange(r string) error { 23 data := strings.Split(r, "-") 24 25 if len(data) != 2 { 26 return fmt.Errorf("range did not contain start and end values (%v)", data) 27 } 28 29 var err error 30 31 start, err := strconv.Atoi(data[0]) 32 if err != nil { 33 return err 34 } 35 36 end, err := strconv.Atoi(data[1]) 37 if err != nil { 38 return err 39 } 40 41 if start < 1 { 42 return fmt.Errorf("range start, %d, is less than 1", start) 43 } 44 45 if end > 99 { 46 return fmt.Errorf("range end, %d, is greather than 99", end) 47 } 48 49 s.start = start 50 s.end = end 51 52 return nil 53 } 54 55 // Pair holds 2 elves sections. 56 type pair struct { 57 elf1 section 58 elf2 section 59 } 60 61 func (p *pair) addPair(input string) error { 62 data := strings.Split(input, ",") 63 64 if len(data) != 2 { 65 return fmt.Errorf("input list doesn't contain two entries (%v)", data) 66 } 67 68 err := p.elf1.addRange(data[0]) 69 if err != nil { 70 return err 71 } 72 73 err = p.elf2.addRange(data[1]) 74 if err != nil { 75 return err 76 } 77 78 return nil 79 } 80 81 func (p *pair) isFullyContained(elfNo int) bool { 82 if elfNo == 1 { 83 return p.elf1.start >= p.elf2.start && p.elf1.end <= p.elf2.end 84 } 85 86 return p.elf2.start >= p.elf1.start && p.elf2.end <= p.elf1.end 87 } 88 89 func (p *pair) isPartiallyContained(elfNo int) bool { 90 if elfNo == 1 { 91 return (p.elf2.start <= p.elf1.start && p.elf1.start <= p.elf2.end) || (p.elf2.start <= p.elf1.end && p.elf1.end <= p.elf2.end) 92 } 93 94 return (p.elf1.start <= p.elf2.start && p.elf2.start <= p.elf1.end) || (p.elf1.start <= p.elf2.end && p.elf2.end <= p.elf1.end) 95 } 96 97 type pairs []pair 98 99 // Setup creates the applications configuration object. 100 func Setup(appName string) Config { 101 102 conf := Config{ 103 appName: appName, 104 inputFileName: "data/" + appName + "/" + appName + "-input.txt", 105 } 106 107 return conf 108 }