find the mode of all keys in a map in go

To find the mode of all keys in a map in Go, we need to first determine the frequency of occurrence of each key in the map. We can do this by creating a new map where the keys are the values of the original map, and the values are the frequency of each key in the original map:

main.go
func modeKeys(m map[interface{}]interface{}) []interface{} {
    freq := make(map[interface{}]int)
    maxFreq := 0

    for _, v := range m {
        freq[v]++
        if freq[v] > maxFreq {
            maxFreq = freq[v]
        }
    }

    // Create a slice to store the mode keys
    modeKeys := make([]interface{}, 0)

    // Find all keys with frequency equal to maxFreq
    for k, v := range m {
        if freq[v] == maxFreq {
            modeKeys = append(modeKeys, k)
        }
    }

    return modeKeys
}
517 chars
24 lines

This function takes in a map with keys of type interface{} and values of type interface{}, and returns a slice of all keys with the highest frequency of occurrence.

To use this function:

main.go
m := map[interface{}]interface{}{
    "a": 1,
    "b": 2,
    "c": 1,
    "d": 3,
    "e": 2,
}

modeKeys := modeKeys(m) // Returns ["b" "e"]
142 chars
10 lines

In this example, the keys "b" and "e" both have a frequency of 2, which is the highest frequency in the map, so they are returned as the mode keys.

related categories

gistlibby LogSnag