Skip to content

Instantly share code, notes, and snippets.

@Napear
Last active November 28, 2022 16:22
Show Gist options
  • Save Napear/df41f13bfb5c10566102 to your computer and use it in GitHub Desktop.
Save Napear/df41f13bfb5c10566102 to your computer and use it in GitHub Desktop.
A function for returning the mode of a slice in Golang
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