-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.go
122 lines (109 loc) · 2.53 KB
/
part2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package day06
import (
"slices"
"github.com/patrick22414/Advent-of-Code-2024/readinput"
)
func DirectionMarker(dx, dy int) byte {
if dx == -1 && dy == 0 {
return Up
} else if dx == 0 && dy == 1 {
return Right
} else if dx == 1 && dy == 0 {
return Down
} else if dx == 0 && dy == -1 {
return Left
}
panic("not a direction")
}
func MarkerDirection(marker byte) (dx, dy int) {
if marker == Up {
dx, dy = -1, 0
} else if marker == Right {
dx, dy = 0, 1
} else if marker == Down {
dx, dy = 1, 0
} else if marker == Left {
dx, dy = 0, -1
} else {
panic("not a starting position")
}
return dx, dy
}
// Given a map of the area and a starting position (x, y), mark the path of the
// patrolling guard. Return if the guard is stuck in a loop (true) or will exit
// the area (false).
func Patrol(area [][]byte, x, y int) (isLoop bool) {
// the starting direction is already marked
dx, dy := MarkerDirection(area[x][y])
area[x][y] = Empty
m, n := len(area), len(area[0]) // size of the area
marker := DirectionMarker(dx, dy)
for {
x1, y1 := x+dx, y+dy
if x1 < 0 || x1 >= m || y1 < 0 || y1 >= n {
// out of bounds
area[x][y] = marker
break
}
if area[x1][y1] == Wall {
// turn right 90 degrees
d := complex(float64(dx), float64(dy))
d *= complex(0, -1)
dx = int(real(d))
dy = int(imag(d))
marker = DirectionMarker(dx, dy)
} else {
if area[x][y] == marker {
return true
}
area[x][y] = marker
x, y = x1, y1
}
}
return false
}
func Part2() int {
area := make([][]byte, 0)
x, y := 0, -1 // guard position
for lineString := range readinput.ReadInput("./input.txt") {
line := []byte(lineString)
area = append(area, line)
if y < 0 {
y = slices.Index(line, Up) // current position of the guard
if y < 0 {
x++
}
}
}
areaClean := slices.Clone(area)
areaCopy := slices.Clone(area)
for i, row := range area {
areaClean[i] = slices.Clone(row)
areaCopy[i] = slices.Clone(row)
}
// mark the area
Patrol(area, x, y)
// then try putting Wall at each marked position
count := 1
countLoops := 0
for i, row := range area {
for j, cell := range row {
if i == x && j == y {
continue // cannot put Wall at Guard position
}
if cell != Empty && cell != Wall {
// fmt.Println(count, "/", total-1) // progress bar
count++
// clear out test area
for ii, rowClean := range areaClean {
copy(areaCopy[ii], rowClean)
}
areaCopy[i][j] = Wall // add a new Wall
if Patrol(areaCopy, x, y) {
countLoops++
}
}
}
}
return countLoops
}