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