find the average of all keys in a map in go

To find the average of all keys in a map in Go, you can iterate over the keys of the map and compute the total sum of the keys. Then, you can divide the total by the number of keys in the map to get the average.

Here's an example code snippet:

main.go
func averageMapKeys(m map[string]int) float64 {
    var total float64
    for k := range m {
        total += float64(k)
    }
    return total / float64(len(m))
}
164 chars
8 lines

This function takes a map of string keys and integer values and returns the average of all the keys in the map. The total variable is initialized to zero and then incremented by the value of each key in the loop. Finally, the total is divided by the number of keys in the map and returned as a float64.

Use the function like this:

main.go
m := map[string]int{
    "apple":  1,
    "banana": 2,
    "cherry": 3,
}
avg := averageMapKeys(m)
fmt.Println(avg) // Output: 6
129 chars
8 lines

related categories

gistlibby LogSnag