part-02.exs 2.0 KB

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