re: AoC Day 1: Chronal Calibration VIEW POST

FULL DISCUSSION
 

Awesome, this is a nice place to discuss the solutions! This is mine, in Elixir:

Common code (used by both part 1 and part 2):

defmodule AoC.DayOne.Common do
  def read_input(path) do
    File.stream!(path)
    |> Stream.map(&String.trim/1)
    |> Stream.filter(fn x -> x != "" end)
    |> Stream.map(&String.trim_trailing/1)
    |> Stream.map(&String.to_integer/1)
    |> Enum.to_list()
  end
end

Part 1


defmodule AoC.DayOne.PartOne do
  alias AoC.DayOne.Common

  def main() do
    Common.read_input("lib/day1/input.txt")
    |> calculate_sum()
    |> IO.puts()
  end

  def calculate_sum(numbers) do
    Enum.sum(numbers)
  end
end

Part 2

defmodule AoC.DayOne.PartTwo do
  alias AoC.DayOne.Common

  def main() do
    Common.read_input("lib/day1/input.txt")
    |> calculate_result()
    |> IO.puts()
  end

  def calculate_result(numbers, frequencies \\ [], base \\ 0, index \\ 0)

  def calculate_result(numbers, frequencies, base, index) when index == length(numbers) do
    calculate_result(numbers, frequencies, base, 0)
  end

  def calculate_result(numbers, frequencies, base, index) do
    base = base + Enum.at(numbers, index)
    if (Enum.member?(frequencies, base)) do
      base
    else
      frequencies = [base | frequencies]
      calculate_result(numbers, frequencies, base, index + 1)
    end
  end
end

If you want, you could check out my full repo on GitHub.

code of conduct - report abuse