diff --git a/stat/count.go b/stat/count.go new file mode 100644 index 0000000000000000000000000000000000000000..f1ebb5ce3a0e4903dae55b45476f9807adb125d3 --- /dev/null +++ b/stat/count.go @@ -0,0 +1,48 @@ +package stat + +import "github.com/viterin/vek" + +// Count 统计 +func Count[T Number | ~bool](x []T) int { + switch vs := any(x).(type) { + case []bool: + return vek.Count(vs) + case []int8: + return __count_go(vs) + case []uint8: + return __count_go(vs) + case []int16: + return __count_go(vs) + case []uint16: + return __count_go(vs) + case []int32: + return __count_go(vs) + case []uint32: + return __count_go(vs) + case []int64: + return __count_go(vs) + case []uint64: + return __count_go(vs) + case []int: + return __count_go(vs) + case []uint: + return __count_go(vs) + case []uintptr: + return __count_go(vs) + case []float32: + return __count_go(vs) + case []float64: + return __count_go(vs) + } + return 0 +} + +func __count_go[T Number](x []T) int { + cnt := 0 + for i := 0; i < len(x); i++ { + if x[i] != 0 { + cnt += 1 + } + } + return cnt +} diff --git a/stat/count_test.go b/stat/count_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ab02dcb7fe77576c158679d02051c75d084bb0b9 --- /dev/null +++ b/stat/count_test.go @@ -0,0 +1,19 @@ +package stat + +import ( + "fmt" + "testing" +) + +func TestCount(t *testing.T) { + d1 := []bool{true, true} + d2 := []bool{true, false} + d3 := []uintptr{0, 1} + d4 := []int{1, 1} + d5 := []float64{1.0, 0} + fmt.Println(Count(d1)) + fmt.Println(Count(d2)) + fmt.Println(Count(d3)) + fmt.Println(Count(d4)) + fmt.Println(Count(d5)) +}