Last active
February 19, 2018 21:44
-
-
Save leoromanovsky/f5b2b984b0f5ee09dc0fdfa734c02ef8 to your computer and use it in GitHub Desktop.
Compute max population given a list of people's birth and death year
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val persons = Seq( | |
Person(2000, 2010), | |
Person(2000, 2005), | |
Person(1990, 2005) | |
) | |
// Create an array of population change. | |
val births = persons.groupBy(_.birthYear).mapValues(_.length) | |
val deaths = persons.groupBy(_.deathYear).mapValues(_.length) | |
val populationChanges = (births.keySet ++ deaths.keySet).map { year => | |
(year, births.getOrElse(year, 0) - deaths.getOrElse(year, 0)) | |
}.toMap | |
println("populationChanges", populationChanges) | |
val sortedYears = populationChanges.keys.toSeq.sorted | |
println(sortedYears) | |
// construct an array of total populations | |
val populations = populationChanges.toSeq | |
.sortBy(_._1) | |
.scanLeft(0) { (a, b) => a + b._2 } | |
.tail | |
.zip(sortedYears) // this is a bit hacky | |
.map{ case(count, year) => (year, count) } | |
println("pop", populations) | |
println("max pop", populations.maxBy(_._2)) // (2000, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment