Advent of Code Solutions
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.

118 lines
1.9 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)
}
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
}