p1
This commit is contained in:
3
2024/02/go.mod
Normal file
3
2024/02/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module main
|
||||||
|
|
||||||
|
go 1.23.3
|
||||||
102
2024/02/main.go
Normal file
102
2024/02/main.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
for _, line := range lines {
|
||||||
|
fmt.Println(line)
|
||||||
|
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++
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(safes)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
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