summaryrefslogtreecommitdiff
path: root/2024/go/src/day6/main.go
diff options
context:
space:
mode:
authoromagdy <omar.professional8777@gmail.com>2024-12-06 21:16:15 +0200
committeromagdy <omar.professional8777@gmail.com>2024-12-06 21:16:15 +0200
commitd588a22bfb5d3a848e2c04eddd1f54d601045e59 (patch)
tree18a94aed5a5d224fe21365b22b4d771869c14ca8 /2024/go/src/day6/main.go
parentf86d2d992f18c8bfc735760f849b1f2c288f1a50 (diff)
downloadaoc-d588a22bfb5d3a848e2c04eddd1f54d601045e59.tar.xz
aoc-d588a22bfb5d3a848e2c04eddd1f54d601045e59.zip
Made isStuck blazingly fast by using an array of booleans to detect the cycle using the guard position and direction instead of of detecting cycle by count
Diffstat (limited to '2024/go/src/day6/main.go')
-rw-r--r--2024/go/src/day6/main.go24
1 files changed, 11 insertions, 13 deletions
diff --git a/2024/go/src/day6/main.go b/2024/go/src/day6/main.go
index 2dc707e..f1505e9 100644
--- a/2024/go/src/day6/main.go
+++ b/2024/go/src/day6/main.go
@@ -114,34 +114,32 @@ func solve_part_one(data string) int {
return trailCount
}
-func isStuck(grid *Grid, gPos [2]int, trials int) bool {
- cnt := 0
- set := make(map[[2]int]struct{})
- set[gPos] = struct{}{}
+func isStuck(grid *Grid, gPos [2]int) bool {
+ n, m := len(*grid), len((*grid)[0])
+ visited := make([]bool, n*m*4)
curOrientation := getOrientation((*grid)[gPos[0]][gPos[1]])
+ visited[((gPos[0]*n)+gPos[1])*4+curOrientation] = true
dx := [4]int{-1, 0, 1, 0} // Up, Right, Down, Left
dy := [4]int{0, 1, 0, -1}
- for trials > 0 {
- prevSize := len(set)
+ for {
nx := gPos[0] + dx[curOrientation]
ny := gPos[1] + dy[curOrientation]
if isValid(grid, nx, ny) {
curPoint := (*grid)[nx][ny]
if !isObstacle(curPoint) {
gPos = [2]int{nx, ny}
- // replaceCharGrid(grid, nx, ny, 'X')
- set[gPos] = struct{}{}
- if prevSize == len(set) {
- cnt++
+ if visited[((nx*n)+ny)*4+curOrientation] {
+ return true
}
+ visited[((nx*n)+ny)*4+curOrientation] = true
} else {
curOrientation = turn90(curOrientation)
}
+ } else {
+ break
}
- trials--
}
-
- return cnt >= len(set)
+ return false
}
func solve_part_two(data string) int {