|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/kfarnung/advent-of-code/2020/lib" |
| 10 | +) |
| 11 | + |
| 12 | +func part1(input string) int64 { |
| 13 | + first, second, err := parseInput(input) |
| 14 | + if err != nil { |
| 15 | + log.Fatal(err) |
| 16 | + } |
| 17 | + |
| 18 | + lib.SortSliceInt64(first) |
| 19 | + lib.SortSliceInt64(second) |
| 20 | + |
| 21 | + sum := int64(0) |
| 22 | + for i := 0; i < len(first); i++ { |
| 23 | + sum += lib.AbsInt64(first[i] - second[i]) |
| 24 | + } |
| 25 | + |
| 26 | + return sum |
| 27 | +} |
| 28 | + |
| 29 | +func part2(input string) int64 { |
| 30 | + first, second, err := parseInput(input) |
| 31 | + if err != nil { |
| 32 | + log.Fatal(err) |
| 33 | + } |
| 34 | + |
| 35 | + sum := int64(0) |
| 36 | + for _, value := range first { |
| 37 | + count := int64(0) |
| 38 | + for _, otherValue := range second { |
| 39 | + if value == otherValue { |
| 40 | + count++ |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + sum += value * count |
| 45 | + } |
| 46 | + |
| 47 | + return sum |
| 48 | +} |
| 49 | + |
| 50 | +func parseInput(input string) ([]int64, []int64, error) { |
| 51 | + var first []int64 |
| 52 | + var second []int64 |
| 53 | + lines := lib.SplitLines(input) |
| 54 | + for _, line := range lines { |
| 55 | + if (len(line)) == 0 { |
| 56 | + continue |
| 57 | + } |
| 58 | + |
| 59 | + splitLine := strings.Split(line, " ") |
| 60 | + firstValue, err := lib.ParseInt64(splitLine[0]) |
| 61 | + if err != nil { |
| 62 | + return nil, nil, err |
| 63 | + } |
| 64 | + |
| 65 | + secondValue, err := lib.ParseInt64(splitLine[len(splitLine)-1]) |
| 66 | + if err != nil { |
| 67 | + return nil, nil, err |
| 68 | + } |
| 69 | + |
| 70 | + first = append(first, firstValue) |
| 71 | + second = append(second, secondValue) |
| 72 | + } |
| 73 | + |
| 74 | + return first, second, nil |
| 75 | +} |
| 76 | + |
| 77 | +func main() { |
| 78 | + name := os.Args[1] |
| 79 | + content, err := lib.LoadFileContent(name) |
| 80 | + if err != nil { |
| 81 | + log.Fatal(err) |
| 82 | + } |
| 83 | + |
| 84 | + fmt.Printf("Part 1: %d\n", part1(content)) |
| 85 | + fmt.Printf("Part 2: %d\n", part2(content)) |
| 86 | +} |
0 commit comments