2018-day01.exs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. ## 2018 ADVENT OF CODE DAY ONE
  2. # part one: given an input of positive and negative integers, return sum of all
  3. # of them
  4. # part two: given same input, return the first duplicated result when summing
  5. # one at a time (repeating input values until a duplicate is found)
  6. ## part one
  7. defmodule PartOne do
  8. # recursive version
  9. def sum_list([head | tail], accumulator) do
  10. sum_list(tail, head + accumulator)
  11. end
  12. def sum_list([], accumulator) do
  13. accumulator
  14. end
  15. # fancy version
  16. def better_sum_list(list, acc) do
  17. Enum.reduce(list, acc, &+/2)
  18. end
  19. end
  20. # test against examples
  21. # (oh god there is a less ugly way to set up these tests)
  22. test1 = PartOne.sum_list([+1, +1, +1],0)
  23. test1b = PartOne.better_sum_list([+1, +1, +1],0)
  24. test2 = PartOne.sum_list([+1, +1, -2],0)
  25. test2b = PartOne.better_sum_list([+1, +1, -2],0)
  26. test3 = PartOne.sum_list([-1, -2, -3],0)
  27. test3b = PartOne.better_sum_list([-1, -2, -3],0)
  28. IO.puts("test 1:")
  29. IO.puts(test1 == 3)
  30. IO.puts("test 1b:")
  31. IO.puts(test1b == 3)
  32. IO.puts("test 2:")
  33. IO.puts(test2 == 0)
  34. IO.puts("test 2b:")
  35. IO.puts(test2b == 0)
  36. IO.puts("test 3:")
  37. IO.puts(test3 == -6)
  38. IO.puts("test 3b:")
  39. IO.puts(test3b == -6)
  40. # using puzzle input
  41. IO.puts("PART ONE SOLUTION:")
  42. list_input = Enum.map(String.split(String.trim(File.read!("2018-day01-input.txt"))), &String.to_integer/1)
  43. # todo: figure out how to pipe and store the result instead, this is ugly af
  44. PartOne.better_sum_list(list_input, 0)
  45. |> IO.puts()
  46. ## part two
  47. defmodule PartTwo do
  48. def sum_list([head | tail], original, acc, master) do
  49. if master[acc] do
  50. acc
  51. else
  52. master = Map.put(master, acc, true)
  53. sum_list(tail, original, head+acc, master)
  54. end
  55. end
  56. def sum_list([], original, acc, master) do
  57. sum_list(original, original, acc, master)
  58. end
  59. end
  60. # tests
  61. IO.puts("2.1: ")
  62. IO.puts(PartTwo.sum_list([+1, -1], [+1, -1], 0, %{}) == 0)
  63. IO.puts("2.2: ")
  64. IO.puts(PartTwo.sum_list([+3, +3, +4, -2, -4], [+3, +3, +4, -2, -4], 0, %{}) == 10)
  65. IO.puts("2.3: ")
  66. IO.puts(PartTwo.sum_list([-6, +3, +8, +5, -6], [-6, +3, +8, +5, -6], 0, %{}) == 5)
  67. IO.puts("2.4: ")
  68. IO.puts(PartTwo.sum_list([+7, +7, -2, -7, -4], [+7, +7, -2, -7, -4], 0, %{}) == 14)
  69. # using puzzle input
  70. IO.puts("PART TWO SOLUTION:")
  71. PartTwo.sum_list(list_input, list_input, 0, %{})
  72. |> IO.puts()