find the median of all keys in a map in go

To find the median of all keys in a map in Go, we need to convert the map keys into a slice, sort the slice, and then find the median.

Here's an example code snippet that does exactly that:

main.go
package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[int]string{
        3: "apple",
        1: "orange",
        2: "banana",
    }

    keys := make([]int, 0, len(m))
    for k := range m {
        keys = append(keys, k)
    }

    sort.Ints(keys)

    var median int
    middle := len(keys) / 2
    if len(keys)%2 == 0 {
        median = (keys[middle-1] + keys[middle]) / 2
    } else {
        median = keys[middle]
    }

    fmt.Println("Median of keys:", median)
}
493 chars
32 lines

In this code snippet, we first create a sample map m with integer keys and string values. Then, we initialize an empty slice keys with an initial length of 0 and capacity equal to the length of the map m.

We then loop through the keys of m using a range loop and append each key to the keys slice.

Next, we sort the keys slice using sort.Ints.

After that, we find the median of the sorted keys slice. We first get the middle index of the slice and check if the length of the slice is even or odd. If it's even, we take the average of the middle two values to get the median. If it's odd, we simply take the value at the middle index of the slice.

Finally, we print the median value.

related categories

gistlibby LogSnag