I have a dictionary of people with their respective births and deaths.
I want to figure out which year had the most people alive.
My currently algorithm appends every year lived by every person into an array and then return the highest occurence. I have a hunch that there is a much neater way to achieve this.
Here is my makeshift brute implementation:
var people = [ "Nicolas": (birth: 1900, death: 1975),
"Vladimir": (birth: 1970, death: 2000),
"Julius": (birth: 1950, death: 1985),
"Alexander": (birth: 1900, death: 1920),
"Obama": (birth: 1910, death: 1920),
"George": (birth: 1915, death: 1920),
"Benjamin": (birth: 1919, death: 1925)]
var yearsArray = [Int]()
var yearOccurrences: [Int:Int] = [:]
for life in people.values {
var birth = life.birth
var death = life.death
for year in birth..<death {
yearsArray.append(year)
}
}
for year in yearsArray {
yearOccurrences[year] = (yearOccurrences[year] ?? 0) + 1
}
(yearOccurrences as! NSDictionary).allKeysForObject(yearOccurrences.values.maxElement()!)
Expected results are 1919 and 1920.
Looking for a more concise and elegant solution in terms of either code or process