From 65eafb1d56cb106f095c8527e11a41c139a8326d Mon Sep 17 00:00:00 2001 From: Mika Suhonen Date: Wed, 4 Dec 2024 18:16:50 +0200 Subject: [PATCH] p1 --- 2024/04/go.mod | 3 ++ 2024/04/main.go | 108 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 2024/04/go.mod create mode 100644 2024/04/main.go diff --git a/2024/04/go.mod b/2024/04/go.mod new file mode 100644 index 0000000..3a3a5a6 --- /dev/null +++ b/2024/04/go.mod @@ -0,0 +1,3 @@ +module main + +go 1.23.3 diff --git a/2024/04/main.go b/2024/04/main.go new file mode 100644 index 0000000..e0e1edf --- /dev/null +++ b/2024/04/main.go @@ -0,0 +1,108 @@ +package main + +import ( + "fmt" + "os" + "strings" +) + +func main() { + + lines, err := parse() + if err != nil { + fmt.Println("Error:", err) + } + + var p1 int = 0 + var p2 int = 0 + + h := len(lines) + w := len(lines[0]) + + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + + if lines[y][x] == 'X' { + // check right + if x <= len(lines[y])-4 { + r := string([]byte{lines[y][x+1], lines[y][x+2], lines[y][x+3]}) + if r == "MAS" { + p1++ + } + } + + // check left + if x >= 3 { + l := string([]byte{lines[y][x-1], lines[y][x-2], lines[y][x-3]}) + if l == "MAS" { + p1++ + } + } + + // check if up possible + if y >= 3 { + u := string([]byte{lines[y-1][x], lines[y-2][x], lines[y-3][x]}) + if u == "MAS" { + p1++ + } + if x >= 3 { + ul := string([]byte{lines[y-1][x-1], lines[y-2][x-2], lines[y-3][x-3]}) + if ul == "MAS" { + p1++ + } + } + if x < w-3 { + ur := string([]byte{lines[y-1][x+1], lines[y-2][x+2], lines[y-3][x+3]}) + if ur == "MAS" { + p1++ + } + } + + } + + // check down + if y <= h-4 { + d := string([]byte{lines[y+1][x], lines[y+2][x], lines[y+3][x]}) + if d == "MAS" { + p1++ + } + if x >= 3 { + dl := string([]byte{lines[y+1][x-1], lines[y+2][x-2], lines[y+3][x-3]}) + if dl == "MAS" { + p1++ + } + } + if x < w-3 { + dr := string([]byte{lines[y+1][x+1], lines[y+2][x+2], lines[y+3][x+3]}) + if dr == "MAS" { + p1++ + } + } + } + } + } + } + + fmt.Println("p1: ", p1) + fmt.Println("p2: ", p2) +} + +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 +}