find the median of all keys in a map in swift

To find the median of all keys in a map in Swift, we first need to extract all the keys from the map and store them in an array. We can then sort the array in ascending order using the sorted() function. Finally, we can calculate the median of the array by checking if the count of elements is even or odd and returning the appropriate value.

Here is the code to find the median of all keys in a map in Swift:

main.swift
let myMap: [Int: String] = [1: "A", 5: "B", 2: "C", 4: "D", 3: "E"]

let keysArray = Array(myMap.keys).sorted()
let count = keysArray.count

if count % 2 == 0 {
    // array has even number of elements, so we need to return the average of the two middle values
    let middleIndex = count / 2
    let median = Double(keysArray[middleIndex] + keysArray[middleIndex - 1]) / 2
    print("Median of map keys: \(median)")
} else {
    // array has odd number of elements, so we can simply return the middle value
    let middleIndex = count / 2
    let median = Double(keysArray[middleIndex])
    print("Median of map keys: \(median)")
}
633 chars
17 lines

In this code, we first define a map myMap with some key-value pairs. We then extract all the keys from this map using the keys property and convert them to an array using the Array() initializer. We then sort this array in ascending order using the sorted() method.

Next, we check if the count of elements in the array is even or odd by using the modulo operator %. If the count is even, we calculate the median by taking the average of the two middle values. If the count is odd, we simply return the middle value.

Finally, we print the median of the map keys to the console using the print() function.

gistlibby LogSnag