From 129387ad2eccaa714cbaa468496b56d10acf9ae6 Mon Sep 17 00:00:00 2001 From: Alexander Avery Date: Tue, 3 Dec 2024 11:19:25 -0500 Subject: [PATCH] factor out layer checking; use slices.Reverse to check for descending levels --- 2024/day02.go | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/2024/day02.go b/2024/day02.go index e3386bd..17a79d5 100644 --- a/2024/day02.go +++ b/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 +}