Skip to content
This repository was archived by the owner on Dec 28, 2024. It is now read-only.

Commit 8de2bb6

Browse files
committed
Add func IsIn2DArray(c, m) bool
Complete method signature: ```go func In2DArray[T any]( c util.Coordinate, m [][]T, ) bool ```
1 parent 3e6d60b commit 8de2bb6

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

common/util/coordinate.go

+10
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,16 @@ type Coordinate struct {
77

88
type Direction = func(c Coordinate) Coordinate
99

10+
func In2DArray[T any](
11+
c Coordinate,
12+
m [][]T,
13+
) bool {
14+
invalid := len(m) == 0 || len(m[0]) == 0 ||
15+
c.X < 0 || c.X >= len(m[0]) ||
16+
c.Y < 0 || c.Y >= len(m)
17+
return !invalid
18+
}
19+
1020
func (c Coordinate) North() Coordinate {
1121
return Coordinate{c.X, c.Y - 1}
1222
}

common/util/coordinate_test.go

+43
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package util
22

33
import (
4+
"fmt"
45
"testing"
56
)
67

@@ -28,3 +29,45 @@ func TestCoordinateDirections(t *testing.T) {
2829
})
2930
}
3031
}
32+
33+
func TestIn2DArray(t *testing.T) {
34+
matrix := [][]int{{0, 0}, {0, 0}}
35+
tests := []struct {
36+
c Coordinate
37+
expected bool
38+
}{
39+
// Top left corner
40+
{Coordinate{X: -1, Y: -1}, false},
41+
{Coordinate{X: +0, Y: -1}, false},
42+
{Coordinate{X: -1, Y: +0}, false},
43+
{Coordinate{X: +0, Y: +0}, true},
44+
45+
// Top right corner
46+
{Coordinate{X: +1, Y: -1}, false},
47+
{Coordinate{X: +2, Y: -1}, false},
48+
{Coordinate{X: +1, Y: +0}, true},
49+
{Coordinate{X: +2, Y: +0}, false},
50+
51+
// Bottom left corner
52+
{Coordinate{X: -1, Y: +1}, false},
53+
{Coordinate{X: +0, Y: +1}, true},
54+
{Coordinate{X: -1, Y: +2}, false},
55+
{Coordinate{X: +0, Y: +2}, false},
56+
57+
// Bottom right corner
58+
{Coordinate{X: +1, Y: +1}, true},
59+
{Coordinate{X: +2, Y: +1}, false},
60+
{Coordinate{X: +1, Y: +2}, false},
61+
{Coordinate{X: +2, Y: +2}, false},
62+
}
63+
64+
for _, test := range tests {
65+
name := fmt.Sprintf("%v in 2D matrix", test.c)
66+
t.Run(name, func(t *testing.T) {
67+
actual := In2DArray(test.c, matrix)
68+
if test.expected != actual {
69+
t.Errorf("expected In2DArray(test.c, matrix) == %v but got %v", test.expected, actual)
70+
}
71+
})
72+
}
73+
}

0 commit comments

Comments
 (0)