Browse Source

factor out layer checking; use slices.Reverse to check for descending levels

master
Alexander Avery 3 weeks ago
parent
commit
129387ad2e
  1. 27
      2024/day02.go

27
2024/day02.go

@ -4,6 +4,7 @@ import (
"bufio"
"fmt"
"io"
"slices"
"strings"
)
@ -13,7 +14,6 @@ func (d Day2) Part1(r io.Reader) string {
s := bufio.NewScanner(r)
var sum int
Scan:
for s.Scan() {
sz := strings.Count(s.Text(), " ") + 1
@ -26,21 +26,13 @@ Scan:
fmt.Sscan(s.Text(), levelprts...)
increasing := level[1]-level[0] > 0
if increasing {
for i := 0; i < len(level)-1; i++ {
if diff := level[i+1] - level[i]; diff > 3 || diff < 1 {
continue Scan
}
}
if layerOk(level) {
sum++
} else {
for i := 0; i < len(level)-1; i++ {
if diff := level[i] - level[i+1]; diff > 3 || diff < 1 {
continue Scan
}
slices.Reverse(level)
if layerOk(level) {
sum++
}
sum++
}
}
@ -124,3 +116,12 @@ Scan:
func inrange(i int) bool {
return i < 4 && i > 0
}
func layerOk(layer []int) bool {
for i := 0; i < len(layer)-1; i++ {
if !inrange(layer[i] - layer[i+1]) {
return false
}
}
return true
}

Loading…
Cancel
Save