Skip to content

Commit

Permalink
Add mode function to mathx package (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristinaleonr authored Apr 24, 2024
1 parent 3867338 commit 96eb26f
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
23 changes: 23 additions & 0 deletions mathx/compare.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,32 @@
package mathx

import "errors"

// Min returns the minimum of two ints.
func Min(a, b int) int {
if a < b {
return a
}
return b
}

// Mode returns the mode of a slice.
func Mode(slice []int64) (int64, error) {
if len(slice) == 0 {
return 0, errors.New("invalid slice")
}

counts := make(map[int64]int64)
var mode int64
var maxCount int64

for _, v := range slice {
counts[v]++
if counts[v] > maxCount {
maxCount = counts[v]
mode = v
}
}

return mode, nil
}
44 changes: 43 additions & 1 deletion mathx/compare_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package mathx

import "testing"
import (
"testing"
)

func TestMin(t *testing.T) {
tests := []struct {
Expand Down Expand Up @@ -50,3 +52,43 @@ func TestMin(t *testing.T) {
})
}
}

func TestMode(t *testing.T) {
tests := []struct {
name string
slice []int64
want int64
wantErr bool
}{
{
name: "empty",
slice: []int64{},
want: 0,
wantErr: true,
},
{
name: "single",
slice: []int64{1, 2, 1, 3},
want: 1,
wantErr: false,
},
{
name: "multiple",
slice: []int64{1, 2, 3, 1, 2},
want: 1,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Mode(tt.slice)
if (err != nil) != tt.wantErr {
t.Errorf("Mode() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("Mode() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 96eb26f

Please sign in to comment.