1
0
aoc-2024/day2.go
2024-12-04 22:45:05 +02:00

110 lines
1.7 KiB
Go

package main
import (
"fmt"
"strconv"
"strings"
)
type Day2Input [][]int64
func Day2Parse(lines []string) (Day2Input, error) {
rows := make([][]int64, len(lines))
for i, line := range lines {
levelsCount := strings.Count(line, " ") + 1
rows[i] = make([]int64, levelsCount)
for j, level := range strings.Split(line, " ") {
number, err := strconv.ParseInt(level, 10, 0)
if err != nil {
return nil, err
}
rows[i][j] = number
}
}
return rows, nil
}
func absInt(value int64) int64 {
if value < 0 {
return -value
} else {
return value
}
}
func Day2IsReportSafe(report []int64) bool {
increasing := false
decreasing := false
for i := range len(report)-1 {
if report[i+1] >= report[i] {
increasing = true
}
if report[i+1] <= report[i] {
decreasing = true
}
if absInt(report[i+1] - report[i]) >= 4 {
return false
}
if increasing && decreasing {
return false
}
}
return !(increasing && decreasing) && (increasing || decreasing)
}
func Day2Part1(lines []string) error {
input, err := Day2Parse(lines)
if err != nil {
return err
}
answer := 0
for _, row := range input {
if Day2IsReportSafe(row) {
answer += 1
}
}
fmt.Println(answer)
return nil
}
func DeleteAtIndex(slice []int64, index int) []int64 {
result := make([]int64, len(slice))
copy(result, slice)
return append(result[:index], result[index+1:]...)
}
func Day2Part2(lines []string) error {
input, err := Day2Parse(lines)
if err != nil {
return err
}
answer := 0
for _, row := range input {
if Day2IsReportSafe(row) {
answer += 1
continue
}
for i := range len(row) {
if Day2IsReportSafe(DeleteAtIndex(row, i)) {
answer += 1
break
}
}
}
fmt.Println(answer)
return nil
}