-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrid.go
132 lines (113 loc) · 2.21 KB
/
grid.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
123
124
125
126
127
128
129
130
131
132
package aoc2023
import "fmt"
type Pos2D struct{ X, Y int }
func (p Pos2D) North() Pos2D { return Pos2D{p.X, p.Y - 1} }
func (p Pos2D) East() Pos2D { return Pos2D{p.X + 1, p.Y} }
func (p Pos2D) South() Pos2D { return Pos2D{p.X, p.Y + 1} }
func (p Pos2D) West() Pos2D { return Pos2D{p.X - 1, p.Y} }
func (p Pos2D) Step(d Dir) Pos2D {
switch d {
case North:
return p.North()
case East:
return p.East()
case South:
return p.South()
case West:
return p.West()
}
panic(fmt.Errorf("unexpected dir: %d", d))
}
type Dir int
const (
North Dir = iota
East
South
West
)
type Grid2D [][]byte
func (g Grid2D) Print() {
for _, row := range g {
fmt.Printf("%s\n", row)
}
}
func (g Grid2D) Get(p Pos2D) (byte, bool) {
if p.Y < 0 || p.Y >= len(g) {
return 0, false
}
if p.X < 0 || p.X >= len(g[p.Y]) {
return 0, false
}
return g[p.Y][p.X], true
}
func (g Grid2D) Set(p Pos2D, b byte) {
g[p.Y][p.X] = b
}
func (g Grid2D) Iter(p Pos2D, d Dir, yield func(p Pos2D, v byte) bool) {
if p.Y < 0 || p.Y >= len(g) {
return
}
if p.X < 0 || p.X >= len(g[p.Y]) {
return
}
switch d {
case North:
NorthIter{g, p.X, p.Y}.Iter(yield)
case East:
EastIter{g, p.X, p.Y}.Iter(yield)
case South:
SouthIter{g, p.X, p.Y}.Iter(yield)
case West:
WestIter{g, p.X, p.Y}.Iter(yield)
default:
panic(fmt.Errorf("unexpected dir: %d", d))
}
}
type SouthIter struct {
g Grid2D
x int
startY int
}
func (r SouthIter) Iter(yield func(p Pos2D, v byte) bool) {
for y := r.startY; y < len(r.g); y++ {
if !yield(Pos2D{r.x, y}, r.g[y][r.x]) {
break
}
}
}
type NorthIter struct {
g Grid2D
x int
startY int
}
func (r NorthIter) Iter(yield func(p Pos2D, v byte) bool) {
for y := r.startY; y >= 0; y-- {
if !yield(Pos2D{r.x, y}, r.g[y][r.x]) {
break
}
}
}
type EastIter struct {
g Grid2D
startX int
y int
}
func (r EastIter) Iter(yield func(p Pos2D, v byte) bool) {
for x := r.startX; x < len(r.g[r.y]); x++ {
if !yield(Pos2D{x, r.y}, r.g[r.y][x]) {
break
}
}
}
type WestIter struct {
g Grid2D
startX int
y int
}
func (r WestIter) Iter(yield func(p Pos2D, v byte) bool) {
for x := r.startX; x >= 0; x-- {
if !yield(Pos2D{x, r.y}, r.g[r.y][x]) {
break
}
}
}