Day02
This commit is contained in:
76
2024/gareth/day02/day02.go
Normal file
76
2024/gareth/day02/day02.go
Normal file
@@ -0,0 +1,76 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user