|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + _ "embed" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | +) |
| 8 | + |
| 9 | +//go:embed input.txt |
| 10 | +var input string |
| 11 | + |
| 12 | +var digitsUnderTest = map[int]struct{}{ |
| 13 | + 1: {}, |
| 14 | + 4: {}, |
| 15 | + 7: {}, |
| 16 | + 8: {}, |
| 17 | +} |
| 18 | + |
| 19 | +func main() { |
| 20 | + if input == "" { |
| 21 | + panic("input cannot be empty") |
| 22 | + } |
| 23 | + |
| 24 | + problems := []*Problem{} |
| 25 | + |
| 26 | + inputstrarr := strings.Split(input, "\n") |
| 27 | + for _, line := range inputstrarr { |
| 28 | + lineSplit := strings.Split(line, " | ") |
| 29 | + segmentValues := strings.Split(lineSplit[0], " ") |
| 30 | + testValues := strings.Split(lineSplit[1], " ") |
| 31 | + |
| 32 | + p := &Problem{ |
| 33 | + segmentValues: segmentValues, |
| 34 | + testValues: testValues, |
| 35 | + } |
| 36 | + // fmt.Printf("%+v\n", p) |
| 37 | + problems = append(problems, p) |
| 38 | + } |
| 39 | + world := &World{ |
| 40 | + problems: problems, |
| 41 | + } |
| 42 | + |
| 43 | + HowManyTimesDoDigitsAppear := world.HowManyTimesDoDigitsAppear(digitsUnderTest) |
| 44 | + fmt.Printf("Answer: %d\n", HowManyTimesDoDigitsAppear) |
| 45 | +} |
| 46 | + |
| 47 | +type World struct { |
| 48 | + problems []*Problem |
| 49 | +} |
| 50 | + |
| 51 | +func (w *World) HowManyTimesDoDigitsAppear(digits map[int]struct{}) (count int) { |
| 52 | + for _, p := range w.problems { |
| 53 | + for _, test := range p.testValues { |
| 54 | + val := p.WhatIsSegmentValue(test) |
| 55 | + // fmt.Printf("%s = %d\n", test, val) |
| 56 | + if _, ok := digits[val]; ok { |
| 57 | + count++ |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + return count |
| 62 | +} |
| 63 | + |
| 64 | +type Problem struct { |
| 65 | + segmentValues []string |
| 66 | + testValues []string |
| 67 | +} |
| 68 | + |
| 69 | +func (p *Problem) WhatIsSegmentValue(testValue string) int { |
| 70 | + // A simple test for getting values 1,4,7,8 is to check length |
| 71 | + // as the number of segments is unique for these values. |
| 72 | + switch len(testValue) { |
| 73 | + case 2: |
| 74 | + return 1 |
| 75 | + case 4: |
| 76 | + return 4 |
| 77 | + case 3: |
| 78 | + return 7 |
| 79 | + case 7: |
| 80 | + return 8 |
| 81 | + } |
| 82 | + |
| 83 | + return 0 |
| 84 | +} |
0 commit comments