fork(1) download
  1. defmodule Population do
  2. def count_people(people) do
  3. people
  4. |> Enum.reduce(%{}, fn (%{ birth: birth, death: death }, acc) ->
  5. acc
  6. |> Map.update(birth, 1, &(&1 + 1))
  7. |> Map.update(death, -1, &(&1 - 1))
  8. end)
  9. |> Enum.scan({0, 0}, fn({ year, population }, { _, population_acc }) -> { year, population + population_acc } end)
  10. |> Enum.max_by(fn({_, year}) -> year end)
  11. end
  12. end
  13.  
  14. people = [
  15. %{ birth: 1920, death: 1950 },
  16. %{ birth: 1920, death: 1980 },
  17. %{ birth: 1940, death: 1990 },
  18. %{ birth: 1930, death: 1940 },
  19. %{ birth: 1970, death: 2010 },
  20. %{ birth: 1920, death: 1960 },
  21. %{ birth: 1720, death: 1860 },
  22. %{ birth: 1730, death: 1810 }
  23. ];
  24.  
  25. people
  26. |> Population.count_people
  27. |> IO.inspect
Success #stdin #stdout 0.4s 29956KB
stdin
Standard input is empty
stdout
{1930, 4}