-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (103 loc) · 2.37 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
func parseInput(content string) [][]int {
lines := strings.Split(string(content), "\n")
values := make([][]int, len(lines))
for i, line := range lines {
numbers := strings.Split(string(line), " ")
linesValues := make([]int, len(numbers))
for j, number := range numbers {
linesValues[j], _ = strconv.Atoi(number)
}
values[i] = linesValues
}
return values
}
func nullVector(values []int) bool {
for _, value := range values {
if value != 0 {
return false
}
}
return true
}
func computeDifferences(values []int) []int {
var differences []int
for i := 0; i < len(values)-1; i++ {
differences = append(differences, values[i+1]-values[i])
}
return differences
}
func estimateNextValue(values []int) int {
if nullVector(values) {
return 0
}
differences := computeDifferences(values)
return values[len(values)-1] + estimateNextValue(differences)
}
func estimateNextValues(values [][]int) []int {
var nextValues []int
for _, line := range values {
nextValues = append(nextValues, estimateNextValue(line))
}
return nextValues
}
func sum(values []int) int {
sum := 0
for _, value := range values {
sum += value
}
return sum
}
func part01(filepath string) (int, error) {
content, err := ioutil.ReadFile(filepath)
if err != nil {
return 0, err
}
values := parseInput(string(content))
nextValues := estimateNextValues(values)
return sum(nextValues), nil
}
func estimatePreviousValue(values []int) int {
if nullVector(values) {
return 0
}
differences := computeDifferences(values)
return values[0] - estimatePreviousValue(differences)
}
func estimatePreviousValues(values [][]int) []int {
var nextValues []int
for _, line := range values {
nextValues = append(nextValues, estimatePreviousValue(line))
}
return nextValues
}
func part02(filepath string) (int, error) {
content, err := ioutil.ReadFile(filepath)
if err != nil {
return 0, err
}
values := parseInput(string(content))
previousValues := estimatePreviousValues(values)
return sum(previousValues), nil
}
func main() {
result, err := part01("input.txt")
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading file:", err)
return
}
fmt.Println("Part 01:", result)
result, err = part02("input.txt")
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading file:", err)
return
}
fmt.Println("Part 02:", result)
}