77 lines
1.3 KiB
Go
77 lines
1.3 KiB
Go
package day02
|
|
|
|
import (
|
|
"math"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func Part1(input string) int {
|
|
total := 0
|
|
lines := strings.Split(input, "\n")
|
|
for _, line := range lines {
|
|
var report []int
|
|
nums := strings.Fields(line)
|
|
for _, num := range nums {
|
|
intnum, _ := strconv.Atoi(num)
|
|
report = append(report, int(intnum))
|
|
}
|
|
if isSafe(report) {
|
|
total++
|
|
}
|
|
}
|
|
return total
|
|
}
|
|
|
|
func Part2(input string) int {
|
|
total := 0
|
|
lines := strings.Split(input, "\n")
|
|
for _, line := range lines {
|
|
var report []int
|
|
nums := strings.Fields(line)
|
|
for _, num := range nums {
|
|
intnum, _ := strconv.Atoi(num)
|
|
report = append(report, int(intnum))
|
|
}
|
|
if isSafeWithDampener(report) {
|
|
total++
|
|
}
|
|
}
|
|
return total
|
|
}
|
|
|
|
func isSafe(report []int) bool {
|
|
increasing := report[1] > report[0]
|
|
decreasing := report[1] < report[0]
|
|
|
|
for i := 1; i < len(report); i++ {
|
|
diff := report[i] - report[i-1]
|
|
absDiff := int(math.Abs(float64(diff)))
|
|
|
|
if absDiff < 1 || absDiff > 3 {
|
|
return false
|
|
}
|
|
|
|
if (diff > 0 && !increasing) || (diff < 0 && !decreasing) {
|
|
return false
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func isSafeWithDampener(report []int) bool {
|
|
if isSafe(report) {
|
|
return true
|
|
}
|
|
|
|
for i := 0; i < len(report); i++ {
|
|
modifiedReport := append(report[:i], report[i+1:]...)
|
|
if isSafe(modifiedReport) {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|