From 29b0095eadc49a8152b29e8c825c20074cb672ef Mon Sep 17 00:00:00 2001 From: wangfeng Date: Mon, 13 Feb 2023 12:16:39 +0800 Subject: [PATCH] =?UTF-8?q?#I6ENG2=20=E5=AE=9E=E7=8E=B0Count=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- stat/count.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++ stat/count_test.go | 19 ++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 stat/count.go create mode 100644 stat/count_test.go diff --git a/stat/count.go b/stat/count.go new file mode 100644 index 0000000..f1ebb5c --- /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 0000000..ab02dcb --- /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)) +} -- Gitee