Skip to content

Commit ddd4d11

Browse files
committed
2024.06 part 2
1 parent e843cb3 commit ddd4d11

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

2024/6-guard/main.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,26 @@ func main() {
3737
}
3838

3939
// Walk the grid
40-
fmt.Println(walkGrid(copyGrid(grid)))
40+
fmt.Println(walkGrid(copyGrid(grid), position{-1, -1}))
41+
42+
// Add random obstacles and test again
43+
var infLoops int
44+
for y := range len(grid) {
45+
for x := range len(grid[0]) {
46+
if walkGrid(copyGrid(grid), position{x, y}) == -1 {
47+
infLoops++
48+
}
49+
}
50+
}
51+
52+
fmt.Println(infLoops)
4153
}
4254

4355
type position struct {
4456
X, Y int
4557
}
4658

47-
func walkGrid(grid [][]byte) int {
59+
func walkGrid(grid [][]byte, obstacle position) int {
4860
guard := position{guardStart.X, guardStart.Y}
4961

5062
stepCount := 1
@@ -58,12 +70,12 @@ func walkGrid(grid [][]byte) int {
5870
return stepCount
5971
}
6072

61-
if grid[ny][nx] == obstacleBlock {
73+
if grid[ny][nx] == obstacleBlock || (nx == obstacle.X && ny == obstacle.Y) {
6274
dx, dy = (dx+1)%4, (dy+1)%4
6375
continue
6476
} else if grid[ny][nx] == 0 {
6577
stepCount++
66-
} else if grid[ny][nx] > 4 {
78+
} else if grid[ny][nx] == 5 {
6779
return -1 // Infinite loop detected!
6880
}
6981

0 commit comments

Comments
 (0)