Browse Source

fix day 2 part 2; when in doubt, use brute force

master
Alexander Avery 3 weeks ago
parent
commit
9399eec934
  1. 73
      2024/day02.go

73
2024/day02.go

@ -39,19 +39,10 @@ func (d Day2) Part1(r io.Reader) string {
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
@ -64,51 +55,15 @@ Scan:
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++
}
}
if layerOkWithDampen(level) {
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++
}
slices.Reverse(level)
if layerOkWithDampen(level) {
sum++
}
sum++
}
}
return printi(sum)
}
@ -125,3 +80,21 @@ func layerOk(layer []int) bool {
}
return true
}
func layerOkWithDampen(layer []int) bool {
layerc := make([]int, len(layer)-1)
for i := 0; i < len(layer)-1; i++ {
if !inrange(layer[i] - layer[i+1]) {
copy(layerc, layer[i:i+1])
for i := range layer {
copy(layerc, layer[:i])
copy(layerc[i:], layer[i+1:])
if layerOk(layerc) {
return true
}
}
return false
}
}
return true
}

Loading…
Cancel
Save