From c9e459edac8d50e12b22a5ead5de6f4dfec29598 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Thu, 27 Oct 2022 17:03:30 +0200 Subject: [PATCH] Add mathext.Min / mathext.Max --- langext/generics.go | 28 ++++++++++++++++++++++++++++ mathext/math.go | 18 ++++++++++++++++++ mathext/statistics.go | 18 ++++++++++-------- 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/langext/generics.go b/langext/generics.go index e295033..8004d8e 100644 --- a/langext/generics.go +++ b/langext/generics.go @@ -3,3 +3,31 @@ package langext type IntConstraint interface { int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 } + +type SignedConstraint interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +type UnsignedConstraint interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +type IntegerConstraint interface { + SignedConstraint | UnsignedConstraint +} + +type FloatConstraint interface { + ~float32 | ~float64 +} + +type ComplexConstraint interface { + ~complex64 | ~complex128 +} + +type OrderedConstraint interface { + IntegerConstraint | FloatConstraint | ~string +} + +type NumberConstraint interface { + IntegerConstraint | FloatConstraint +} diff --git a/mathext/math.go b/mathext/math.go index bf71435..3cf7651 100644 --- a/mathext/math.go +++ b/mathext/math.go @@ -1,5 +1,7 @@ package mathext +import "gogs.mikescher.com/BlackForestBytes/goext/langext" + func AvgFloat64(arr []float64) float64 { return SumFloat64(arr) / float64(len(arr)) } @@ -11,3 +13,19 @@ func SumFloat64(arr []float64) float64 { } return sum } + +func Max[T langext.OrderedConstraint](v1 T, v2 T) T { + if v1 > v2 { + return v1 + } else { + return v2 + } +} + +func Min[T langext.OrderedConstraint](v1 T, v2 T) T { + if v1 < v2 { + return v1 + } else { + return v2 + } +} diff --git a/mathext/statistics.go b/mathext/statistics.go index bceed45..52216c7 100644 --- a/mathext/statistics.go +++ b/mathext/statistics.go @@ -1,26 +1,28 @@ package mathext -func Sum(v []float64) float64 { - total := float64(0) +import "gogs.mikescher.com/BlackForestBytes/goext/langext" + +func Sum[T langext.NumberConstraint](v []T) T { + total := T(0) for _, v := range v { total += v } return total } -func Mean(v []float64) float64 { - return Sum(v) / float64(len(v)) +func Mean[T langext.FloatConstraint](v []T) T { + return Sum(v) / T(len(v)) } -func Median(v []float64) float64 { +func Median[T langext.FloatConstraint](v []T) T { if len(v)%2 == 1 { return v[len(v)/2] } else { - return (v[len(v)/2-1] + v[len(v)/2]) / float64(2) + return (v[len(v)/2-1] + v[len(v)/2]) / T(2) } } -func Min(v []float64) float64 { +func ArrMin[T langext.OrderedConstraint](v []T) T { r := v[0] for _, val := range v { if val < r { @@ -30,7 +32,7 @@ func Min(v []float64) float64 { return r } -func Max(v []float64) float64 { +func ArrMax[T langext.OrderedConstraint](v []T) T { r := v[0] for _, val := range v { if val > r {