Skip to content

Commit acdda10

Browse files
committed
feat: Implement 2024 day 2 part 1
1 parent 6451ed4 commit acdda10

File tree

1 file changed

+65
-2
lines changed

1 file changed

+65
-2
lines changed

internal/puzzles/solutions/2024/day02/solution.go

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,14 @@
22
package day02
33

44
import (
5+
"bufio"
6+
"bytes"
7+
"fmt"
58
"io"
9+
"strconv"
610

711
"github.com/obalunenko/advent-of-code/internal/puzzles"
12+
"github.com/obalunenko/advent-of-code/internal/puzzles/common/utils"
813
)
914

1015
func init() {
@@ -22,9 +27,67 @@ func (s solution) Day() string {
2227
}
2328

2429
func (s solution) Part1(input io.Reader) (string, error) {
25-
return "", puzzles.ErrNotImplemented
30+
scanner := bufio.NewScanner(input)
31+
32+
isSafe := func(line []int) bool {
33+
var asc, desc bool
34+
35+
for i, val := range line {
36+
if i == 0 {
37+
continue
38+
}
39+
40+
if line[i-1] < val {
41+
if desc {
42+
return false
43+
}
44+
45+
asc = true
46+
}
47+
48+
if line[i-1] > val {
49+
if asc {
50+
return false
51+
}
52+
53+
desc = true
54+
}
55+
56+
diff := val - line[i-1]
57+
if diff < 0 {
58+
diff = -diff
59+
}
60+
61+
if diff < 1 || diff > 3 {
62+
return false
63+
}
64+
}
65+
66+
return true
67+
}
68+
69+
var safeCount int
70+
71+
for scanner.Scan() {
72+
line := scanner.Bytes()
73+
74+
numbers, err := utils.ParseInts(bytes.NewReader(line), " ")
75+
if err != nil {
76+
return "", fmt.Errorf("failed to parse input line: %w", err)
77+
}
78+
79+
if isSafe(numbers) {
80+
safeCount++
81+
}
82+
}
83+
84+
if err := scanner.Err(); err != nil {
85+
return "", fmt.Errorf("failed to read input: %w", err)
86+
}
87+
88+
return strconv.Itoa(safeCount), nil
2689
}
2790

28-
func (s solution) Part2(input io.Reader) (string, error) {
91+
func (s solution) Part2(_ io.Reader) (string, error) {
2992
return "", puzzles.ErrNotImplemented
3093
}

0 commit comments

Comments
 (0)