package adventoc2024 import ( "bufio" "fmt" "io" "slices" "strings" ) type Day2 struct{} func (d Day2) Part1(r io.Reader) string { s := bufio.NewScanner(r) var sum int for s.Scan() { sz := strings.Count(s.Text(), " ") + 1 level := make([]int, sz) levelprts := make([]any, sz) for i := range levelprts { levelprts[i] = &level[i] } fmt.Sscan(s.Text(), levelprts...) if layerOk(level) { sum++ } else { slices.Reverse(level) if layerOk(level) { sum++ } } } return printi(sum) } // part 2 does not yet work because this code makes a false assumption. // that assumption is that in order to fix a broken level, you can only skip the // one that made it broken. // // this is not true because of the following level // 5 6 3 2 // 5 and 6 would be OK, so the algorithm will blame the 3 and attempt to skip it. // the real solution however, is to skip the 6 because it would be fine if all descending func (d Day2) Part2(r io.Reader) string { s := bufio.NewScanner(r) var sum int Scan: for s.Scan() { sz := strings.Count(s.Text(), " ") + 1 level := make([]int, sz) levelprts := make([]any, sz) for i := range levelprts { levelprts[i] = &level[i] } fmt.Sscan(s.Text(), levelprts...) increasing := level[1]-level[0] > 0 var dampened bool if increasing { for i := 0; i < len(level)-1; i++ { if diff := level[i+1] - level[i]; !inrange(diff) { if dampened { continue Scan } if i+2 > len(level)-1 { continue Scan } d2 := level[i+2] - level[i] if !inrange(d2) { continue Scan } dampened = true i++ } } sum++ } else { for i := 0; i < len(level)-1; i++ { if diff := level[i] - level[i+1]; !inrange(diff) { if dampened { continue Scan } if i+2 > len(level)-1 { continue Scan } d2 := level[i] - level[i+2] if !inrange(d2) { continue Scan } dampened = true i++ } } sum++ } } return printi(sum) } 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 }