Last active
November 28, 2022 16:22
-
-
Save Napear/df41f13bfb5c10566102 to your computer and use it in GitHub Desktop.
A function for returning the mode of a slice in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getMode(testArray []int) (mode int) { | |
// Create a map and populated it with each value in the slice | |
// mapped to the number of times it occurs | |
countMap := make(map[int]int) | |
for _, value := range testArray { | |
countMap[value] += 1 | |
} | |
// Find the smallest item with greatest number of occurance in | |
// the input slice | |
max := 0 | |
for _, key := range testArray { | |
freq := countMap[key] | |
if freq > max { | |
mode = key | |
max = freq | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment