You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
126 lines
2.3 KiB
126 lines
2.3 KiB
package adventoc2024
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
)
|
|
|
|
type Day2 struct{}
|
|
|
|
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
|
|
|
|
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
|
|
if increasing {
|
|
for i := 0; i < len(level)-1; i++ {
|
|
if diff := level[i+1] - level[i]; diff > 3 || diff < 1 {
|
|
continue Scan
|
|
}
|
|
}
|
|
sum++
|
|
} else {
|
|
for i := 0; i < len(level)-1; i++ {
|
|
if diff := level[i] - level[i+1]; diff > 3 || diff < 1 {
|
|
continue Scan
|
|
}
|
|
}
|
|
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
|
|
}
|
|
|