find the mode of a list of numbers in go

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.go
package main

import "fmt"

func mode(numbers []int) int {
    count := make(map[int]int)

    // Count the frequency of each number
    for _, num := range numbers {
        count[num]++
    }

    // Find the number with the highest frequency
    max := 0
    mode := 0
    for num, freq := range count {
        if freq > max {
            max = freq
            mode = num
        }
    }

    return mode
}

func main() {
    nums := []int{1, 2, 2, 3, 3, 3}
    fmt.Println(mode(nums)) // Output: 3
}
506 chars
30 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.

related categories

gistlibby LogSnag