aoc/2024/day-06/partone.go.txt
2024-12-06 14:17:39 +01:00

123 lines
2.7 KiB
Plaintext

package day06
import (
"bufio"
"fmt"
"log"
"os"
)
type Position struct {
X, Y int
}
var (
Up = Position{-1, 0}
Down = Position{1, 0}
Left = Position{0, -1}
Right = Position{0, 1}
)
func main() {
file, err := os.Open("./input_test.txt")
if err != nil {
log.Fatalf("failed to open file: %s\n", err)
}
defer file.Close()
s := bufio.NewScanner(file)
var board [][]rune
var coveredPositions map[Position]bool
var guardCurrentPosition Position
var guardCurrentDirection Position
coveredPositions = make(map[Position]bool)
i := 0
for s.Scan() {
var boardLine []rune
j := 0
for _, char := range s.Text() {
boardLine = append(boardLine, char)
if char == '^' {
guardCurrentDirection = Up
}
if char == '>' {
guardCurrentDirection = Right
}
if char == 'v' {
guardCurrentDirection = Down
}
if char == '<' {
guardCurrentDirection = Left
}
if char == '#' || char == '.' {
j++
continue
}
currentPos := Position{i, j}
guardCurrentPosition = currentPos
coveredPositions[currentPos] = true
j++
}
board = append(board, boardLine)
i++
}
// fmt.Println(guardCurrentDirection, guardCurrentPosition)
solvePart1(board, &coveredPositions, guardCurrentPosition, guardCurrentDirection)
// for k, p := range coveredPositions {
// fmt.Printf("x: %d\ty: %d\tcovered: %t\n", k.X, k.Y, p)
// }
// fmt.Println(coveredPositions)
total2 := 0
fmt.Println("result part1:", len(coveredPositions))
fmt.Println("result part2:", total2)
}
func solvePart1(board [][]rune, coveredPositions *map[Position]bool, guardCurrentPosition Position, guardCurrentDirection Position) {
for {
next, err := getNextByDirection(board, guardCurrentPosition, guardCurrentDirection)
if err != nil {
return
}
if next == '#' {
if guardCurrentDirection == Up {
guardCurrentDirection = Right
continue
}
if guardCurrentDirection == Right {
guardCurrentDirection = Down
continue
}
if guardCurrentDirection == Down {
guardCurrentDirection = Left
continue
}
if guardCurrentDirection == Left {
guardCurrentDirection = Up
continue
}
}
guardCurrentPosition.X += guardCurrentDirection.X
guardCurrentPosition.Y += guardCurrentDirection.Y
(*coveredPositions)[Position{guardCurrentPosition.X, guardCurrentPosition.Y}] = true
}
}
func getNextByDirection(board [][]rune, pos Position, dir Position) (rune, error) {
// fmt.Printf("x: %d, y: %d\tdx: %d, dy: %d\n", pos.X, pos.Y, dir.X, dir.Y)
newX := pos.X + dir.X
newY := pos.Y + dir.Y
// Check if the new position is out of bounds
if newX < 0 || newX >= len(board) || newY < 0 || newY >= len(board[0]) {
return 0, fmt.Errorf("position out of bounds: (%d, %d)", newX, newY)
}
return board[newX][newY], nil
}