find the average of all values in a map in go

To find the average of all values in a map in go, you can iterate over the map and sum up all of the values, then divide the sum by the number of values in the map.

main.go
func findAverageValue(m map[string]int) float64 {
    var sum int
    for _, v := range m {
        sum += v
    }
    return float64(sum) / float64(len(m))
}
159 chars
8 lines

In the above code snippet, we define a function findAverageValue that takes in a map m of type map[string]int and returns a float64 representing the average of all values in the map. We initialize a variable sum to zero and then iterate over the map using a for loop. At each iteration, we add the value to the sum variable. Finally, we divide the sum by the length of the map to get the average value, and return it as a float64.

related categories

gistlibby LogSnag