@@ -3,14 +3,16 @@ package main
3
3
import (
4
4
"bufio"
5
5
"fmt"
6
- "github.com/gdejong/advent-of-code-2024/internal"
6
+ "github.com/gdejong/advent-of-code-2024/internal/input"
7
+ "github.com/gdejong/advent-of-code-2024/internal/math"
8
+ "github.com/gdejong/advent-of-code-2024/internal/must"
9
+ "github.com/gdejong/advent-of-code-2024/internal/slices"
7
10
"os"
8
- "strconv"
9
11
"strings"
10
12
)
11
13
12
14
func main () {
13
- f := internal . Must (os .Open ("cmd/day2/real_input.txt" ))
15
+ f := must . NoError (os .Open ("cmd/day2/real_input.txt" ))
14
16
15
17
fmt .Println (part1 (f ))
16
18
}
@@ -22,50 +24,34 @@ func part1(f *os.File) int {
22
24
for s .Scan () {
23
25
line := s .Text ()
24
26
25
- fields := strings .Fields (line )
26
- levels := make ([]int , len (fields ))
27
+ levels := input .ToIntegers (strings .Fields (line ))
27
28
28
- // Convert to integer values
29
- for k , v := range fields {
30
- levels [k ] = internal .Must (strconv .Atoi (v ))
31
- }
32
-
33
- // Calculate the differences
34
- diffs := make ([]int , len (levels )- 1 )
35
- for index := range len (levels ) - 1 {
36
- diffs [index ] = levels [index + 1 ] - levels [index ]
37
- }
38
-
39
- allIncreasing := func (val int ) bool { return val > 0 }
40
- allDecreasing := func (val int ) bool { return val < 0 }
41
- allBetweenOneAndThree := func (val int ) bool { return Abs (val ) >= 1 && Abs (val ) <= 3 }
42
-
43
- isAllIncreasing := All (diffs , allIncreasing )
44
- isAllDecreasing := All (diffs , allDecreasing )
45
- IsAllDifferByAtLeastOneAndAtMostThree := All (diffs , allBetweenOneAndThree )
46
-
47
- if (isAllIncreasing || isAllDecreasing ) && IsAllDifferByAtLeastOneAndAtMostThree {
29
+ if isSafeReport (levels ) {
48
30
safeCounter ++
49
31
}
50
-
51
32
}
52
33
53
34
return safeCounter
54
35
}
55
36
56
- func Abs (value int ) int {
57
- if value < 0 {
58
- value = value * - 1
37
+ func isSafeReport (levels []int ) bool {
38
+ // Calculate the differences
39
+ diffs := make ([]int , len (levels )- 1 )
40
+ for index := range len (levels ) - 1 {
41
+ diffs [index ] = levels [index + 1 ] - levels [index ]
59
42
}
60
43
61
- return value
62
- }
44
+ allIncreasing := func (val int ) bool { return val > 0 }
45
+ allDecreasing := func (val int ) bool { return val < 0 }
46
+ allBetweenOneAndThree := func (val int ) bool { return math .Abs (val ) >= 1 && math .Abs (val ) <= 3 }
63
47
64
- func All [T any ](ts []T , pred func (T ) bool ) bool {
65
- for _ , t := range ts {
66
- if ! pred (t ) {
67
- return false
68
- }
48
+ isAllIncreasing := slices .All (diffs , allIncreasing )
49
+ isAllDecreasing := slices .All (diffs , allDecreasing )
50
+ IsAllDifferByAtLeastOneAndAtMostThree := slices .All (diffs , allBetweenOneAndThree )
51
+
52
+ if (isAllIncreasing || isAllDecreasing ) && IsAllDifferByAtLeastOneAndAtMostThree {
53
+ return true
69
54
}
70
- return true
55
+
56
+ return false
71
57
}
0 commit comments