Skip to content

Instantly share code, notes, and snippets.

@leoromanovsky
Last active February 19, 2018 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoromanovsky/f5b2b984b0f5ee09dc0fdfa734c02ef8 to your computer and use it in GitHub Desktop.
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
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