-
Notifications
You must be signed in to change notification settings - Fork 49
/
compute.go
80 lines (74 loc) · 1.76 KB
/
compute.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package stl4go
// SumAs summarize all elements in a.
// returns the result as type R, this is useful when T is too small to hold the result.
// Complexity: O(len(a)).
func SumAs[R, T Numeric](a []T) R {
switch zero := T(0); any(zero).(type) {
case int8, int16, int32, int, int64:
var total int64
for _, v := range a {
total += int64(v)
}
return R(total)
case uint8, uint16, uint32, uint, uint64, uintptr:
var total uint64
for _, v := range a {
total += uint64(v)
}
return R(total)
default:
var total float64
for _, v := range a {
total += float64(v)
}
return R(total)
}
}
// Sum summarize all elements in a.
// returns the result as type R, you should use SumAs if T can't hold the result.
// Complexity: O(len(a)).
func Sum[T Numeric](a []T) T {
return SumAs[T](a)
}
// AverageAs returns the average value of a as type R.
func AverageAs[R, T Numeric](a []T) R {
return SumAs[R](a) / R(len(a))
}
// Average returns the average value of a.
func Average[T Numeric](a []T) T {
var zero T // NOTE: convert 0 to interface have no malloc
switch any(zero).(type) {
case int, int8, uint8, int16, uint16, int32, uint32:
return T(AverageAs[int64](a))
case uint64:
return T(AverageAs[uint64](a))
case float32, float64:
return T(AverageAs[float64](a))
}
// int64, uint64, uintptr ...
return AverageAs[T](a)
}
// Count returns the number of elements in the slice equals to x.
//
// Complexity: O(len(a)).
func Count[T comparable](a []T, x T) int {
c := 0
for _, v := range a {
if v == x {
c++
}
}
return c
}
// CountIf returns the number of elements in the slice which pred returns true.
//
// Complexity: O(len(a)).
func CountIf[T comparable](a []T, pred func(T) bool) int {
c := 0
for _, v := range a {
if pred(v) {
c++
}
}
return c
}