2024/day2/puzzle1.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
package main import ( "bufio" "errors" "fmt" "os" "strconv" "strings" ) func main() { file, _ := os.Open("input") defer file.Close() scanner := bufio.NewScanner(file) safeLevels := 0 for scanner.Scan() { line := scanner.Text() level := strings.Split(line, " ") numbas := make([]int, len(level)) for i, s := range level { numbas[i], _ = strconv.Atoi(s) } increases, err := seqIncreases(numbas) if err != nil { continue } decreases, err := seqDecreases(numbas) if err != nil { continue } if increases > 0 && decreases > 0 { continue } safeLevels += 1 } fmt.Println(safeLevels) } // calculate sequential increases in da numbas func seqIncreases(numbas []int) (int, error) { count := 0 for i := range numbas { // stop if we're about to go out-of-bounds with // our naive comparison stuff if i+1 == len(numbas) { break } if difference(numbas[i], numbas[i+1]) > 3 { return -1, errors.New("difference greater than 3") } if difference(numbas[i], numbas[i+1]) == 0 { return -1, errors.New("same numbers detected") } if numbas[i] < numbas[i+1] { count += 1 } } return count, nil } // calculate decreases increases in da numbas func seqDecreases(numbas []int) (int, error) { count := 0 for i := range numbas { if i+1 == len(numbas) { break } if difference(numbas[i], numbas[i+1]) > 3 { return -1, errors.New("difference greater than 3") } if difference(numbas[i], numbas[i+1]) == 0 { return -1, errors.New("same numbers detected") } if numbas[i] > numbas[i+1] { count += 1 } } return count, nil } func difference(i1 int, i2 int) int { if i1 > i2 { return i1 - i2 } return i2 - i1 }