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

Day 2

2021/day2.livemd

Day 2

Input

processed =
  IO.gets(:input)
  |> String.split(~r{\s}, trim: true)
  |> Enum.chunk_every(2)
  |> Enum.map(fn [x, y] -> {String.to_atom(x), String.to_integer(y)} end)

Part 1

processed
|> Enum.reduce(
  [0, 0],
  fn {command, n}, [x, y] ->
    case command do
      :forward ->
        [x + n, y]

      :up ->
        [x, y - n]

      :down ->
        [x, y + n]
    end
  end
)
|> Enum.product()

Part 2

processed
|> Enum.reduce(
  [0, 0, 0],
  fn {command, n}, [x, y, aim] ->
    case command do
      :forward ->
        [x + n, y + aim * n, aim]

      :up ->
        [x, y, aim - n]

      :down ->
        [x, y, aim + n]
    end
  end
)
|> Enum.take(2)
|> Enum.product()