find the mode of all values in a map in go

To find the mode of all values in a map, we can first loop over the map to obtain its values and store them in a slice. Next, we can create a new map to count the frequency of each value in the slice. Finally, we can loop over the frequency map to find the key with the highest value, which represents the mode.

Here's an example implementation:

main.go
func mode(m map[string]int) string {
    // Get all values in a slice
    values := []int{}
    for _, v := range m {
        values = append(values, v)
    }

    // Count frequency of each value
    freq := make(map[int]int)
    for _, v := range values {
        freq[v]++
    }

    // Find the key with the highest value
    maxVal := 0
    modeVal := 0
    for k, v := range freq {
        if v > maxVal {
            maxVal = v
            modeVal = k
        }
    }

    return modeVal
}
497 chars
26 lines

In this example, we assume a map where the keys are strings and the values are integers. The mode function returns the mode value as a string. If there are multiple values with the same highest frequency, the function returns the first value encountered.

related categories

gistlibby LogSnag