Add mathext.Min / mathext.Max

This commit is contained in:
Mike Schwörer 2022-10-27 17:03:30 +02:00
parent 3717eeb515
commit c9e459edac
Signed by: Mikescher
GPG Key ID: D3C7172E0A70F8CF
3 changed files with 56 additions and 8 deletions

View File

@ -3,3 +3,31 @@ package langext
type IntConstraint interface { type IntConstraint interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 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
}

View File

@ -1,5 +1,7 @@
package mathext package mathext
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
func AvgFloat64(arr []float64) float64 { func AvgFloat64(arr []float64) float64 {
return SumFloat64(arr) / float64(len(arr)) return SumFloat64(arr) / float64(len(arr))
} }
@ -11,3 +13,19 @@ func SumFloat64(arr []float64) float64 {
} }
return sum 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
}
}

View File

@ -1,26 +1,28 @@
package mathext package mathext
func Sum(v []float64) float64 { import "gogs.mikescher.com/BlackForestBytes/goext/langext"
total := float64(0)
func Sum[T langext.NumberConstraint](v []T) T {
total := T(0)
for _, v := range v { for _, v := range v {
total += v total += v
} }
return total return total
} }
func Mean(v []float64) float64 { func Mean[T langext.FloatConstraint](v []T) T {
return Sum(v) / float64(len(v)) return Sum(v) / T(len(v))
} }
func Median(v []float64) float64 { func Median[T langext.FloatConstraint](v []T) T {
if len(v)%2 == 1 { if len(v)%2 == 1 {
return v[len(v)/2] return v[len(v)/2]
} else { } 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] r := v[0]
for _, val := range v { for _, val := range v {
if val < r { if val < r {
@ -30,7 +32,7 @@ func Min(v []float64) float64 {
return r return r
} }
func Max(v []float64) float64 { func ArrMax[T langext.OrderedConstraint](v []T) T {
r := v[0] r := v[0]
for _, val := range v { for _, val := range v {
if val > r { if val > r {