part-01.exs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. defmodule FileHandling do
  2. def read_lines filename do
  3. File.stream!(filename)
  4. |> Stream.map(&String.trim_trailing/1)
  5. end
  6. end
  7. defmodule RockPaperScissors do
  8. def outcome(:rock, :rock) do :draw end
  9. def outcome(:rock, :paper) do :win end
  10. def outcome(:rock, :scissors) do :loss end
  11. def outcome(:paper, :rock) do :loss end
  12. def outcome(:paper, :paper) do :draw end
  13. def outcome(:paper, :scissors) do :win end
  14. def outcome(:scissors, :rock) do :win end
  15. def outcome(:scissors, :paper) do :loss end
  16. def outcome(:scissors, :scissors) do :draw end
  17. def outcome_score(:loss) do 0 end
  18. def outcome_score(:draw) do 3 end
  19. def outcome_score(:win) do 6 end
  20. def choice_score(:rock) do 1 end
  21. def choice_score(:paper) do 2 end
  22. def choice_score(:scissors) do 3 end
  23. def input_to_rps("A") do :rock end
  24. def input_to_rps("B") do :paper end
  25. def input_to_rps("C") do :scissors end
  26. def input_to_rps("X") do :rock end
  27. def input_to_rps("Y") do :paper end
  28. def input_to_rps("Z") do :scissors end
  29. def round_to_rps([p1_input, p2_input]) do
  30. {input_to_rps(p1_input), input_to_rps(p2_input)}
  31. end
  32. def round_score({p1, p2}) do
  33. (outcome(p1, p2) |> outcome_score) + (choice_score p2)
  34. end
  35. def line_score(line) do
  36. String.split(line, " ") |> round_to_rps |> round_score
  37. end
  38. end
  39. # Need to wrap the code in a function to be able to see the struct.
  40. defmodule Main do
  41. def main do
  42. lines_stream = FileHandling.read_lines "input"
  43. result = lines_stream
  44. |> Stream.map(&RockPaperScissors.line_score/1)
  45. |> Enum.to_list
  46. |> Enum.sum
  47. IO.puts "total score: #{result}"
  48. end
  49. end
  50. Main.main