Compare commits
2 Commits
62342c7aa9
...
bc168219f3
| Author | SHA1 | Date | |
|---|---|---|---|
| bc168219f3 | |||
| 9b098af432 |
3
2024/02/go.mod
Normal file
3
2024/02/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module main
|
||||
|
||||
go 1.23.3
|
||||
115
2024/02/main.go
Normal file
115
2024/02/main.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user