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

Commit 8f8c026

Browse files
committed
Add Matrix::Set
1 parent e523fd8 commit 8f8c026

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

common/util/matrix.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,16 @@ func (m Matrix[T]) GetOrDefault(
9090
}
9191
return v, nil
9292
}
93+
94+
func (m Matrix[T]) Set(
95+
x int,
96+
y int,
97+
value T,
98+
) error {
99+
if !m.IsInMatrix(x, y) {
100+
return fmt.Errorf("invalid point (%d,%d)", x, y)
101+
}
102+
103+
m.matrix[y][x] = value
104+
return nil
105+
}

common/util/matrix_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package util
22

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

@@ -215,3 +216,45 @@ func TestMatrix_GetOrDefault(t *testing.T) {
215216
}
216217
}
217218
}
219+
220+
func TestMatrix_Set(t *testing.T) {
221+
raw := [][]int{{1, 1}, {1, 1}}
222+
m, creationErr := NewMatrixFromRows(raw)
223+
coords := []Coordinate{c(0, 0), c(0, 1), c(1, 0), c(1, 1)}
224+
225+
for _, point := range coords {
226+
name := fmt.Sprintf("Changing at point %v", point)
227+
t.Run(name, func(t *testing.T) {
228+
if creationErr != nil {
229+
t.Error("Initialization of matrix failed")
230+
}
231+
232+
curV, err := m.Get(point.X, point.Y)
233+
if err != nil {
234+
t.Error("Failed to get current value")
235+
}
236+
237+
expectedNewV := curV * 10
238+
err = m.Set(point.X, point.Y, expectedNewV)
239+
if err != nil {
240+
t.Error("Failed to set value")
241+
}
242+
243+
actualNewV, err := m.Get(point.X, point.Y)
244+
if err != nil {
245+
t.Error("Failed to get new value")
246+
}
247+
248+
if actualNewV != expectedNewV {
249+
t.Errorf("Expected new value %d, but was %d", expectedNewV, actualNewV)
250+
}
251+
})
252+
253+
t.Run("Setting point outside of matrix", func(t *testing.T) {
254+
err := m.Set(2, 1, 1337)
255+
if err == nil {
256+
t.Error("Expected error from setting (2,1), but got nil")
257+
}
258+
})
259+
}
260+
}

0 commit comments

Comments
 (0)