aoc2024/day-02/internal/one/solve.go

49 lines
722 B
Go
Raw Normal View History

2024-12-02 19:28:55 +00:00
package one
import (
"bufio"
"bytes"
"io"
)
type comparator func([]int, int) bool
2024-12-06 19:57:07 +00:00
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
2024-12-03 02:29:28 +00:00
sum, err := parseLines(r)
if err != nil {
return 0, err
}
2024-12-02 19:28:55 +00:00
return sum, nil
}
2024-12-03 02:29:28 +00:00
func parseLines(r io.Reader) (int, error) {
var (
cmpIncrease = func(nums []int, i int) bool {
return nums[i-1] >= nums[i]
}
cmpDecrease = func(nums []int, i int) bool {
return nums[i-1] <= nums[i]
}
)
2024-12-02 19:28:55 +00:00
var sum int
scanner := bufio.NewScanner(r)
for scanner.Scan() {
nums := intsFromString(scanner.Text())
if check(nums, cmpIncrease) || check(nums, cmpDecrease) {
2024-12-02 19:28:55 +00:00
sum++
}
}
2024-12-03 02:29:28 +00:00
if err := scanner.Err(); err != nil {
return 0, err
}
return sum, nil
2024-12-02 19:28:55 +00:00
}