aoc/2024/day-02/main.go

100 lines
1.5 KiB
Go

package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
func main() {
file, err := os.Open("./input.txt")
if err != nil {
log.Fatalf("failed to open file: %s\n", err)
}
defer file.Close()
s := bufio.NewScanner(file)
result1 := 0
result2 := 0
for s.Scan() {
t := s.Text()
strs := strings.Split(t, " ")
var ints = []int{}
for _, i := range strs {
j, err := strconv.Atoi(i)
if err != nil {
log.Fatalf("failed to convert string to int: %s\n", err)
}
ints = append(ints, j)
}
safe := checkSafe(ints)
if safe {
result1++
result2++
} else {
for idxRemove := 0; idxRemove < len(ints); idxRemove++ {
var new_ints []int
for idx, i := range ints {
if idx == idxRemove { continue }
new_ints = append(new_ints, i)
}
safe := checkSafe(new_ints)
if safe {
result2++
break
}
}
}
}
fmt.Println("Result1: ", result1)
fmt.Println("Result2: ", result2)
}
func checkSafe(nums []int) bool {
var prev int
var current int
var isIncreasing bool
isSafe := true
for idx, num := range nums {
current = num
if idx == 0 {
prev = num
continue
}
if prev == current {
isSafe = false
break
}
if idx == 1 {
isIncreasing = (prev < current)
}
diff := int(math.Abs(float64(prev) - float64(current)))
if diff < 1 || diff > 3 {
isSafe = false
}
if isIncreasing && (prev > current) {
isSafe = false
}
if !isIncreasing && (prev < current) {
isSafe = false
}
prev = num
}
return isSafe
}