Compare commits

...

2 Commits

Author SHA1 Message Date
bc168219f3 p2 2024-12-02 17:28:47 +02:00
9b098af432 p1 2024-12-02 17:03:01 +02:00
2 changed files with 118 additions and 0 deletions

3
2024/02/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module main
go 1.23.3

115
2024/02/main.go Normal file
View File

@@ -0,0 +1,115 @@
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
const (
Increasing = 1
Decreasing = -1
)
func absInt(x int) int {
return absDiffInt(x, 0)
}
func absDiffInt(x, y int) int {
if x < y {
return y - x
}
return x - y
}
func checkDirection(x int) int {
switch {
case x < 0:
return Increasing
case x > 0:
return Decreasing
default:
return 0
}
}
func checklevel(report []int) bool {
dir := checkDirection(report[0] - report[1])
for i := 0; i < len(report)-1; i++ {
zero := report[i]
one := report[i+1]
diff := zero - one
if newDir := checkDirection(diff); newDir != dir {
return false
}
absDiff := absInt(diff)
if absDiff < 1 || absDiff > 3 {
return false
}
}
return true
}
func main() {
lines, err := parse()
if err != nil {
fmt.Println("Error:", err)
}
var safes = 0
var safes2 = 0
for _, line := range lines {
numbers := strings.Fields(line)
report := make([]int, len(numbers))
for i, num := range numbers {
x, err := strconv.Atoi(num)
if err != nil {
panic(err)
}
report[i] = x
}
if checklevel(report) {
safes++
safes2++
} else {
var checks = 0
for j := 0; j < len(report); j++ {
copyArray := make([]int, len(report))
copy(copyArray, report)
report2 := append(copyArray[:j], copyArray[j+1:]...)
if checklevel(report2) {
checks++
}
}
if checks >= 1 {
safes2++
}
}
}
fmt.Println("p1: ", safes)
fmt.Println("p2: ", safes2)
}
func parse() ([]string, error) {
if len(os.Args) < 2 {
return nil, fmt.Errorf("no file provided")
}
filePath := os.Args[1]
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("error opening file: %v", err)
}
chunks := strings.Split(string(data), "\n")
var nonEmpthyChunks = []string{}
for _, chunk := range chunks {
if chunk != "" {
nonEmpthyChunks = append(nonEmpthyChunks, chunk)
}
}
return nonEmpthyChunks, nil
}