find the median of all values in a map in go

To find the median of all values in a map in Go, we can follow these steps:

  1. Extract all values from the map and store them in a slice.
  2. Sort the slice.
  3. Check if the length of the slice is even or odd.
  4. If the length is even then return the average of the middle two values.
  5. If the length is odd then return the middle value.

Here's the code:

main.go
package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]int{"a": 1, "b": 3, "c": 2, "d": 5, "e": 4}

    values := make([]int, 0, len(m))
    for _, v := range m {
        values = append(values, v)
    }

    sort.Ints(values)

    median := 0.0
    l := len(values)
    if l%2 == 0 {
        median = float64(values[l/2-1]+values[l/2]) / 2.0
    } else {
        median = float64(values[l/2])
    }

    fmt.Println("Median:", median)
}
464 chars
28 lines

In this example, we have a map m with some integer values. We extract all the values and store them in a slice values. Then we sort the slice using sort.Ints. After that, we find the median by checking the length of the slice l. If l is even then we take the average of the middle two values, and if l is odd then we return the middle value. Finally, we print the median using fmt.Println.

related categories

gistlibby LogSnag