Skip to content

Commit 96eb26f

Browse files
Add mode function to mathx package (#184)
1 parent 3867338 commit 96eb26f

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

mathx/compare.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,32 @@
11
package mathx
22

3+
import "errors"
4+
35
// Min returns the minimum of two ints.
46
func Min(a, b int) int {
57
if a < b {
68
return a
79
}
810
return b
911
}
12+
13+
// Mode returns the mode of a slice.
14+
func Mode(slice []int64) (int64, error) {
15+
if len(slice) == 0 {
16+
return 0, errors.New("invalid slice")
17+
}
18+
19+
counts := make(map[int64]int64)
20+
var mode int64
21+
var maxCount int64
22+
23+
for _, v := range slice {
24+
counts[v]++
25+
if counts[v] > maxCount {
26+
maxCount = counts[v]
27+
mode = v
28+
}
29+
}
30+
31+
return mode, nil
32+
}

mathx/compare_test.go

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package mathx
22

3-
import "testing"
3+
import (
4+
"testing"
5+
)
46

57
func TestMin(t *testing.T) {
68
tests := []struct {
@@ -50,3 +52,43 @@ func TestMin(t *testing.T) {
5052
})
5153
}
5254
}
55+
56+
func TestMode(t *testing.T) {
57+
tests := []struct {
58+
name string
59+
slice []int64
60+
want int64
61+
wantErr bool
62+
}{
63+
{
64+
name: "empty",
65+
slice: []int64{},
66+
want: 0,
67+
wantErr: true,
68+
},
69+
{
70+
name: "single",
71+
slice: []int64{1, 2, 1, 3},
72+
want: 1,
73+
wantErr: false,
74+
},
75+
{
76+
name: "multiple",
77+
slice: []int64{1, 2, 3, 1, 2},
78+
want: 1,
79+
wantErr: false,
80+
},
81+
}
82+
for _, tt := range tests {
83+
t.Run(tt.name, func(t *testing.T) {
84+
got, err := Mode(tt.slice)
85+
if (err != nil) != tt.wantErr {
86+
t.Errorf("Mode() error = %v, wantErr %v", err, tt.wantErr)
87+
return
88+
}
89+
if got != tt.want {
90+
t.Errorf("Mode() = %v, want %v", got, tt.want)
91+
}
92+
})
93+
}
94+
}

0 commit comments

Comments
 (0)