MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Mode

Function Mode

math/mode.go:21–47  ·  view source on GitHub ↗
(numbers []T)

Source from the content-addressed store, hash-verified

19var ErrEmptySlice = errors.New("empty slice provided")
20
21func Mode[T constraints.Number](numbers []T) (T, error) {
22
23 countMap := make(map[T]int)
24
25 n := len(numbers)
26
27 if n == 0 {
28 return 0, ErrEmptySlice
29 }
30
31 for _, number := range numbers {
32 countMap[number]++
33 }
34
35 var mode T
36 count := 0
37
38 for k, v := range countMap {
39 if v > count {
40 count = v
41 mode = k
42 }
43 }
44
45 return mode, nil
46
47}

Callers 1

testModeFrameworkFunction · 0.92

Calls

no outgoing calls

Tested by 1

testModeFrameworkFunction · 0.74