Skip to content

Commit

Permalink
Merge pull request #4 from lovung/feat/matrix/add-nearby-func
Browse files Browse the repository at this point in the history
[Matrix] Add nearby function
  • Loading branch information
lovung authored Aug 7, 2023
2 parents a7badc7 + d8aadb2 commit e63832d
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 2 deletions.
13 changes: 13 additions & 0 deletions maths/operators.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,16 @@ func Sum[T constraints.Ordered](a ...T) T {
}
return sum
}

func GCD[T constraints.Integer](a, b T) T {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return GCD(a%b, b)
}
return GCD(a, b%a)
}
7 changes: 7 additions & 0 deletions maths/operators_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,10 @@ func TestSum(t *testing.T) {
assert.Equal(t, 10, Sum(1, 2, 3, 4))
assert.Equal(t, "abcd", Sum("a", "b", "c", "d"))
}

func TestGCD(t *testing.T) {
assert.Equal(t, 10, GCD(10, 20))
assert.Equal(t, 5, GCD(15, 20))
assert.Equal(t, 15, GCD(15, 0))
assert.Equal(t, 4, GCD(12, 16))
}
17 changes: 15 additions & 2 deletions matrix/matrix.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ type Matrix[T any] struct {
defaultVal T
}

var dir = [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}

type CellFn[T any] func(val T, i, j int)

// New m row, n col matrix
func New[T any](m, n int, defaultVal ...T) *Matrix[T] {
data := make([][]T, m)
Expand Down Expand Up @@ -70,10 +74,19 @@ func (mat *Matrix[T]) UpdateAt(i, j int, val T) {
mat.data[i][j] = val
}

func (mat *Matrix[T]) ForEach(f func(val T, i, j int)) {
func (mat *Matrix[T]) ForEach(f CellFn[T]) {
for i := range mat.data {
for j := range mat.data[i] {
f(mat.data[i][j], i, j)
f(mat.At(i, j), i, j)
}
}
}

func (mat *Matrix[T]) DoWithNearBy(i, j int, f CellFn[T]) {
for _, d := range dir {
x, y := i+d[0], j+d[1]
if mat.InBound(x, y) {
f(mat.At(x, y), x, y)
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions matrix/matrix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,11 @@ func Test_Matrix(t *testing.T) {
})
assert.Equal(t, 7, sum)
assert.Equal(t, -1, mat.Data()[0][2])
mat.DoWithNearBy(0, 0, func(_ int, i, j int) { mat.UpdateAt(i, j, 0) })
sum = 0
mat.ForEach(func(val int, _, _ int) {
sum += val
})
assert.Equal(t, 5, sum)
})
}

0 comments on commit e63832d

Please sign in to comment.