Day One - Part One

Advent of Code with Elixir : part 1 of 1 published on Jun 06, 2016

Day One of the Advent of Code has Santa processing directions going up and down floors in a super massive apartment building.

The problem

Santa is trying to deliver presents in a large apartment building, but he can’t find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.

The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.

Examples

  • (()) and ()() both result in floor 0.
  • ((( and (()(()( both result in floor 3.
  • ))((((( also results in floor 3.
  • ()) and ))( both result in floor -1 (the first basement level).
  • ))) and )())()) both result in floor -3.

Watch me work through the problem

The code

I decided to use doctests to test my code as I wrote the solution. For my solution, I use recursion and pattern matching to iterate over the input summing up the changes in the floor.

defmodule Advent.DayOne do
  @doc """
  Returns the floor Santa ends up on

  ## Examples
    iex> Advent.DayOne.find_floor("(())")
    0
    iex> Advent.DayOne.find_floor("()()")
    0
    iex> Advent.DayOne.find_floor("(((")
    3
    iex> Advent.DayOne.find_floor("(()(()(")
    3
    iex> Advent.DayOne.find_floor("))(((((")
    3
    iex> Advent.DayOne.find_floor("())")
    -1
    iex> Advent.DayOne.find_floor("))(")
    -1
    iex> Advent.DayOne.find_floor(")))")
    -3
    iex> Advent.DayOne.find_floor(")())())")
    -3
  """
  def find_floor(input) do
    input |> String.split("") |> _process
  end

  defp _process(["("|chars]), do: 1 + _process(chars)
  defp _process([")"|chars]), do: -1 + _process(chars)
  defp _process(_), do: 0

Feedback

What do you think of my solution? What refactoring or changes would you recommend?

Continue on with Advent of Code with Elixir