part-02.exs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. defmodule FileHandling do
  2. def read_lines filename do
  3. File.stream!(filename)
  4. |> Stream.map(&String.trim_trailing/1)
  5. |> Enum.to_list
  6. end
  7. end
  8. defmodule ListProcessing do
  9. # separate lists at "" element
  10. def split_at_nil(nil, acc) do {:cont, Enum.reverse(acc), []} end
  11. def split_at_nil(elem, acc) do {:cont, [elem | acc]} end
  12. def remaining_elems [] do {:cont, []} end
  13. def remaining_elems other do {:cont, Enum.reverse(other), []} end
  14. def lines_to_integer enum do
  15. enum |> Enum.map(
  16. fn
  17. "" -> nil
  18. number_string -> String.to_integer(number_string, 10)
  19. end
  20. )
  21. end
  22. end
  23. # Need to wrap the code in a function to be able to see the struct.
  24. defmodule Main do
  25. def main do
  26. lines = FileHandling.read_lines "input"
  27. calories = ListProcessing.lines_to_integer lines
  28. calories_grouped = Enum.chunk_while(
  29. calories,
  30. [],
  31. &ListProcessing.split_at_nil/2,
  32. &ListProcessing.remaining_elems/1
  33. )
  34. calories_summed_per_elf = Enum.map(
  35. calories_grouped,
  36. fn [] -> 0; calories -> Enum.sum calories end
  37. )
  38. calories_sorted_per_elf = Enum.sort(
  39. calories_summed_per_elf,
  40. fn calories1, calories2 -> calories1 >= calories2 end
  41. )
  42. result = Enum.take(calories_sorted_per_elf, 3) |> Enum.sum
  43. IO.puts("calories carried by the 3 elves carring the most calories summed: #{result}")
  44. end
  45. end
  46. Main.main