To find the mode of a list of numbers in Go, we can use an array or slice to count the frequency of each number, then loop through the array/slice to find the number with the highest frequency.
Here's an example implementation using a slice:
main.go506 chars30 lines
In the mode
function, we first create a map called count
to store the frequency of each number. Then, we loop through the input numbers
slice and update the frequency count for each number using count[num]++
.
After all the numbers have been counted, we loop through the count
map to find the number with the highest frequency. We maintain two variables: max
(the current highest frequency we've seen so far) and mode
(the number with the highest frequency). If we encounter a number with a frequency greater than max
, we update max
and mode
.
Finally, we return the mode
as our result.
gistlibby LogSnag