Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Advent of Code 2021 / D01

day01.livemd

Advent of Code 2021 / D01

Sonar Sweep Part 1

testReport = [199, 200, 208, 210, 200, 207, 240, 269, 260, 263]
report =
  "inputs/day01.txt"
  |> File.read!()
  |> String.split(~r/\n/, trim: true)
  |> Enum.map(&String.to_integer/1)

I feel like this can be done with Enum.reduceinstead of just counting the “peaks”.

Lets see how this solutions plays out.

defmodule Sonar do
  def depthReport([]), do: []
  def depthReport([_head | []]), do: []

  def depthReport([head | tail]) do
    # IO.puts("head #{inspect(head)} \t tail #{inspect(tail)}")

    [if(head < hd(tail), do: :up, else: :down) | depthReport(tail)]
  end

  def is_up(a) when is_atom(a), do: a == :up
end

testReport
|> Sonar.depthReport()
|> Enum.filter(&amp;Sonar.is_up/1)
# should be 7
|> length

Now for the actual data:

report
|> Sonar.depthReport()
|> Enum.filter(&amp;Sonar.is_up/1)
# should be 1292
|> length

1292 is right!

Sonar Sweep Part 2

testReport
|> Enum.chunk_every(3, 1, :discard)
|> Enum.map(&amp;Enum.sum/1)
|> Sonar.depthReport()
|> Enum.filter(&amp;Sonar.is_up/1)
|> length
report
|> Enum.chunk_every(3, 1, :discard)
|> Enum.map(&amp;Enum.sum/1)
|> Sonar.depthReport()
|> Enum.filter(&amp;Sonar.is_up/1)
|> length

From the community:

File.stream!("inputs/day01.txt")
|> Stream.map(&amp;String.trim/1)
|> Stream.map(&amp;String.to_integer/1)
|> Stream.chunk_every(2, 1, :discard)
|> Enum.count(fn [a, b] -> a < b end)
|> IO.inspect()

Stream is way faster. Must be because it’s not creating any intermediate repsentations. Which is why I can’t use the String.split(~r/\n/, trim: true) function directly.