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

Commit 309577b

Browse files
committed
Add CountInMatrix method for Matrix struct
1 parent 8df4b35 commit 309577b

File tree

2 files changed

+52
-4
lines changed

2 files changed

+52
-4
lines changed

common/util/matrix.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ import (
77

88
type Matrix[T any] struct {
99
RawMatrix [][]T
10-
MaxX int
11-
MaxY int
10+
MaxX int
11+
MaxY int
1212
}
1313

1414
type IntMatrix = Matrix[int]
@@ -42,8 +42,8 @@ func NewMatrixFromRows[T any](
4242

4343
return Matrix[T]{
4444
RawMatrix: matrix,
45-
MaxX: maxX,
46-
MaxY: maxY,
45+
MaxX: maxX,
46+
MaxY: maxY,
4747
}, nil
4848
}
4949

@@ -103,3 +103,18 @@ func (m Matrix[T]) Set(
103103
m.RawMatrix[y][x] = value
104104
return nil
105105
}
106+
107+
func CountInMatrix[T comparable](
108+
m Matrix[T],
109+
value T,
110+
) int {
111+
count := 0
112+
for x := 0; x <= m.MaxX; x++ {
113+
for y := 0; y <= m.MaxY; y++ {
114+
if m.RawMatrix[y][x] == value {
115+
count += 1
116+
}
117+
}
118+
}
119+
return count
120+
}

common/util/matrix_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,3 +258,36 @@ func TestMatrix_Set(t *testing.T) {
258258
})
259259
}
260260
}
261+
262+
func TestCountInMatrix(t *testing.T) {
263+
m, err := NewMatrixFromRows([][]int{{1, 2, 3, 1}, {2, 3, 3, 1}, {3, 1, 2, 1}})
264+
count1 := 5
265+
count2 := 3
266+
count3 := 4
267+
count4 := 0
268+
269+
if err != nil {
270+
t.Error("Failed to construct matrix")
271+
}
272+
var count int
273+
274+
count = CountInMatrix(m, 1)
275+
if count != count1 {
276+
t.Errorf("Expected %d number of ones, got %d", count1, count)
277+
}
278+
279+
count = CountInMatrix(m, 2)
280+
if count != count2 {
281+
t.Errorf("Expected %d number of ones, got %d", count2, count)
282+
}
283+
284+
count = CountInMatrix(m, 3)
285+
if count != count3 {
286+
t.Errorf("Expected %d number of ones, got %d", count3, count)
287+
}
288+
289+
count = CountInMatrix(m, 4)
290+
if count != count4 {
291+
t.Errorf("Expected %d number of ones, got %d", count4, count)
292+
}
293+
}

0 commit comments

Comments
 (0)