part-01.exs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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
  37. [] -> 0
  38. calories -> Enum.sum calories
  39. end
  40. )
  41. calories_sorted_per_elf = Enum.sort(
  42. calories_summed_per_elf,
  43. fn calories1, calories2 -> calories1 >= calories2 end
  44. )
  45. IO.puts("most calories carried by any elf: #{List.first(calories_sorted_per_elf)}")
  46. end
  47. end
  48. Main.main