forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mode.go
45 lines (32 loc) · 773 Bytes
/
mode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// mode.go
// author(s): [CalvinNJK] (https://github.com/CalvinNJK)
// description: Finding Mode Value In an Array
// see mode.go
package math
import (
"errors"
"github.com/TheAlgorithms/Go/constraints"
)
// ErrEmptySlice is the error returned by functions in math package when
// an empty slice is provided to it as argument when the function expects
// a non-empty slice.
var ErrEmptySlice = errors.New("empty slice provided")
func Mode[T constraints.Number](numbers []T) (T, error) {
countMap := make(map[T]int)
n := len(numbers)
if n == 0 {
return 0, ErrEmptySlice
}
for _, number := range numbers {
countMap[number]++
}
var mode T
count := 0
for k, v := range countMap {
if v > count {
count = v
mode = k
}
}
return mode, nil
}