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.
100 lines
1.5 KiB
100 lines
1.5 KiB
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)
|
|
}
|
|
|
|
func (d Day2) Part2(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 layerOkWithDampen(level) {
|
|
sum++
|
|
} else {
|
|
slices.Reverse(level)
|
|
if layerOkWithDampen(level) {
|
|
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
|
|
}
|
|
|
|
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
|
|
}
|
|
|