fork(2) 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. |> IO.inspect
  10. |> Enum.scan({0, 0}, fn({ year, population }, { _, population_acc }) ->
  11. IO.puts year
  12. { year, population + population_acc }
  13. end)
  14. |> Enum.max_by(fn({_, year}) -> year end)
  15. end
  16. end
  17.  
  18. IO.puts "There are 32 unique years in this list. Notice that they're traversed in order"
  19. 0..31
  20. |> Enum.map(&(%{ birth: &1, death: 31 - &1 }))
  21. |> Population.count_people
  22. |> IO.inspect
  23.  
  24. IO.puts "There are 33 in this one...hmmm..."
  25. 0..32
  26. |> Enum.map(&(%{ birth: &1, death: 32 - &1 }))
  27. |> Population.count_people
  28. |> IO.inspect
  29.  
Success #stdin #stdout 0.47s 30432KB
stdin
Standard input is empty
stdout
There are 32 unique years in this list. Notice that they're traversed in order
%{0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0,
  9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0,
  17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0, 24 => 0,
  25 => 0, 26 => 0, 27 => 0, 28 => 0, 29 => 0, 30 => 0, 31 => 0}
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
{0, 0}
There are 33 in this one...hmmm...
%{11 => 0, 26 => 0, 15 => 0, 20 => 0, 17 => 0, 25 => 0, 13 => 0, 0 => 0, 8 => 0,
  7 => 0, 1 => 0, 32 => 0, 3 => 0, 6 => 0, 2 => 0, 10 => 0, 9 => 0, 19 => 0,
  14 => 0, 5 => 0, 18 => 0, 31 => 0, 22 => 0, 29 => 0, 21 => 0, 27 => 0,
  24 => 0, 30 => 0, 23 => 0, 28 => 0, 16 => 0, 4 => 0, 12 => 0}
11
26
15
20
17
25
13
0
8
7
1
32
3
6
2
10
9
19
14
5
18
31
22
29
21
27
24
30
23
28
16
4
12
{11, 0}