Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mathutil: add median utility #517

Merged
merged 2 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions pkg/utils/mathutil/mathutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mathutil
import (
"fmt"
"math"
"slices"

"golang.org/x/exp/constraints"
)
Expand Down Expand Up @@ -49,3 +50,17 @@ func Avg[V constraints.Integer](arr ...V) (V, error) {

return total / V(len(arr)), nil
}

// Median mirrors implementation with generics: https://github.com/montanaflynn/stats/blob/249b5aaa10484bb7e8f3b866b0925aaebdac8170/median.go#L6
func Median[V constraints.Integer](arr ...V) (V, error) {
slices.Sort(arr)

l := len(arr)
if l == 0 {
return 0, fmt.Errorf("empty input")
}
if l%2 == 0 {
return Avg(arr[l/2-1 : l/2+1]...)
}
return arr[l/2], nil
}
17 changes: 17 additions & 0 deletions pkg/utils/mathutil/mathutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,20 @@ func TestAvg(t *testing.T) {
r, err = Avg(a...)
assert.ErrorContains(t, err, "overflow: array len")
}

func TestMedian(t *testing.T) {
// happy path len = odd
v, err := Median(2, 1, 5, 4, 3)
assert.NoError(t, err)
assert.Equal(t, 3, v)

// happy path len = even
v, err = Median(10, 11, 1, 2)
assert.NoError(t, err)
assert.Equal(t, 6, v)

// zero input
v, err = Median[int]()
assert.Error(t, err)
assert.Equal(t, 0, v)
}
Loading