|
| 1 | +// --- Day 9: Mirage Maintenance --- |
| 2 | +// https://adventofcode.com/2023/day/9 |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "bufio" |
| 7 | + "log" |
| 8 | + "os" |
| 9 | + |
| 10 | + "github.com/alkurbatov/adventofcode/internal/parsers" |
| 11 | +) |
| 12 | + |
| 13 | +func readInput(path string) ([][]int, error) { |
| 14 | + input, err := os.Open(path) |
| 15 | + if err != nil { |
| 16 | + return nil, err |
| 17 | + } |
| 18 | + defer input.Close() |
| 19 | + |
| 20 | + scanner := bufio.NewScanner(input) |
| 21 | + result := make([][]int, 0) |
| 22 | + |
| 23 | + for scanner.Scan() { |
| 24 | + sequence, err := parsers.ReadNumbers(scanner.Text()) |
| 25 | + if err != nil { |
| 26 | + return nil, err |
| 27 | + } |
| 28 | + |
| 29 | + result = append(result, sequence) |
| 30 | + } |
| 31 | + |
| 32 | + if err := scanner.Err(); err != nil { |
| 33 | + return nil, err |
| 34 | + } |
| 35 | + |
| 36 | + return result, nil |
| 37 | +} |
| 38 | + |
| 39 | +func calcPredictions(values []int) (left, right int) { |
| 40 | + stepDiff := make([]int, 0) |
| 41 | + allZeroes := true |
| 42 | + |
| 43 | + for i := 1; i < len(values); i++ { |
| 44 | + nextValue := values[i] - values[i-1] |
| 45 | + |
| 46 | + if nextValue != 0 { |
| 47 | + allZeroes = false |
| 48 | + } |
| 49 | + |
| 50 | + stepDiff = append(stepDiff, nextValue) |
| 51 | + } |
| 52 | + |
| 53 | + if allZeroes { |
| 54 | + return values[0], values[len(values)-1] |
| 55 | + } |
| 56 | + |
| 57 | + left, right = calcPredictions(stepDiff) |
| 58 | + |
| 59 | + return values[0] - left, right + values[len(values)-1] |
| 60 | +} |
| 61 | + |
| 62 | +func main() { |
| 63 | + input, err := readInput("2023/9/input.txt") |
| 64 | + if err != nil { |
| 65 | + log.Printf("Failed to read data from input.txt: %v", err) |
| 66 | + return |
| 67 | + } |
| 68 | + |
| 69 | + var firstPartResult, secondPartResult int |
| 70 | + |
| 71 | + for _, history := range input { |
| 72 | + left, right := calcPredictions(history) |
| 73 | + |
| 74 | + firstPartResult += right |
| 75 | + secondPartResult += left |
| 76 | + } |
| 77 | + |
| 78 | + log.Printf("Part 1 result: %d", firstPartResult) |
| 79 | + log.Printf("Part 2 result: %d", secondPartResult) |
| 80 | +} |
0 commit comments