How to find an average for dictionary in Swift?

Viewed 615

I have a dictionary, let's say

let gamePrices = [
"Shooter": [40,60,80],
"RTS": [15,35,55]
"RPG": [5,40,70]
]
avgGamePrices(dictionary: [String: Int]) -> Double {
var total = 0;
for int in dictionary {
total += int
} 

(i suppose, using of int is wrong here) And i don't understand how to get each genre avg price, and total avg price (of all 9 values). I don't even know how to get total here, how should i "mention" the ints or strings of a dictionary in for loop? For default array i'd use

for number in numbers {
total += number
}
let numbersTotal = Int(numbers.count);
let average = total/numbersTotal;
return (Double(average);
2 Answers

To get the average of all prices you need to first get all prices from your dictionary then you can calculate the average. It is not the same as calculating the average of the averages:

let gamePrices = [
    "Shooter": [40,60,80],
    "RTS":     [15,35,55],
    "RPG":     [5,40,70]]

let allPrices = gamePrices.flatMap(\.value)
let sum = allPrices.reduce(.zero, +)
let average = Double(sum) / Double(allPrices.count)  //  44.44444444444444

To get the maximum price for each genre:

let maxPrices: [(genre: String, maxPrice: Int)] = gamePrices.map { ($0, $1.max() ?? .zero)}  // [(genre "Shooter", maxPrice 80), (genre "RTS", maxPrice 55), (genre "RPG", maxPrice 70)]

for (genre, max) in maxPrices {
    print("Genre:", genre, "Max price:", max)
}

If you search a total AVG, so something like this:

func avgGamePrices(dictionary: [String: [Int]]) -> Double {
var total = 0;
var countElem = 0

for obj in dictionary {
    countElem += obj.value.count
    for v in obj.value {
        total += v
    }
}

return Double(total / countElem)

}

calling:

avgGamePrices(dictionary: gamePrices)

otherwise for each key:

func avg(for key: String, dictionary: [String: [Int]]) -> Double {
var total = 0;
let countElem = (dictionary[key] ?? []).count

for v in (dictionary[key] ?? []) {
    total += v
}

return Double(total / countElem)

}

and you can call in this way (passing a single key of your dictionary like a param):

avg(for: "RTS", dictionary: gamePrices)
Related