Skip to content

Commit

Permalink
sum
Browse files Browse the repository at this point in the history
  • Loading branch information
lxzan committed Dec 25, 2023
1 parent 55343cb commit e1cb064
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
8 changes: 7 additions & 1 deletion algorithm/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,15 @@ func UniqueBy[T any, K cmp.Ordered, A ~[]T](arr A, getKey func(item T) K) A {
return arr
}

// Sum 求和
func Sum[T cmp.Number](arr []T) T {
var sum T
return Reduce(arr, sum, func(s T, item T) T { return s + item })
}

// Reduce 对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,
// 最后将其结果汇总为单个返回值。
func Reduce[T any, S any](initialValue S, arr []T, reducer func(s S, item T) S) S {
func Reduce[T any, S any](arr []T, initialValue S, reducer func(s S, item T) S) S {
for _, item := range arr {
initialValue = reducer(initialValue, item)
}
Expand Down
10 changes: 8 additions & 2 deletions algorithm/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ func TestIsZero(t *testing.T) {
func TestReduce(t *testing.T) {
t.Run("", func(t *testing.T) {
var arr = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var sum = Reduce(0, arr, func(summarize int, item int) int {
var sum = Reduce(arr, 0, func(summarize int, item int) int {
return summarize + item
})
assert.Equal(t, sum, 55)
Expand All @@ -196,10 +196,16 @@ func TestReduce(t *testing.T) {
t.Run("", func(t *testing.T) {
var arr = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var m = hashmap.New[int, struct{}](10)
Reduce(m, arr, func(s hashmap.HashMap[int, struct{}], item int) hashmap.HashMap[int, struct{}] {
Reduce(arr, m, func(s hashmap.HashMap[int, struct{}], item int) hashmap.HashMap[int, struct{}] {
s.Set(item, struct{}{})
return s
})
assert.ElementsMatch(t, m.Keys(), []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
})
}

func TestSum(t *testing.T) {
assert.Equal(t, Sum([]int{}), 0)
assert.Equal(t, Sum([]int{1, 3, 5, 7, 9}), 25)
assert.Equal(t, Sum([]uint32{1, 3, 5, 7, 9}), uint32(25))
}

0 comments on commit e1cb064

Please sign in to comment.