aoc2024/day-02/internal/two/solve.go
onyx-and-iris a6295375aa remove internal/util
move cmpIncrease, cmpDecrease into parseLines
2025-01-07 17:19:24 +00:00

55 lines
904 B
Go

package two
import (
"bufio"
"bytes"
"io"
)
type comparator func([]int, int) bool
type dampener func([]int, comparator, int) bool
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
sum, err := parseLines(r)
if err != nil {
return 0, err
}
return sum, nil
}
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]
}
)
var sum int
scanner := bufio.NewScanner(r)
for scanner.Scan() {
nums := intsFromString(scanner.Text())
if check(withDampener, nums, cmpIncrease) || check(withDampener, nums, cmpDecrease) {
sum++
}
}
if err := scanner.Err(); err != nil {
return 0, err
}
return sum, nil
}
func check(fn dampener, nums []int, cmp comparator) bool {
var count int
return fn(nums, cmp, count)
}