Sarat Chandra - Programming and Tech

Thoughts about Tech, Programming and Random things

Solving Advent of Code Day 2 with Elixir

Posted at — Dec 9, 2015

This is the second post in the series of solving Advent of code with Elixir.

defmodule Advent2 do
  def run(input) do
    total_area = input
                 |> File.read!
                 |> String.split("\n", trim: true)
                 |> Enum.map(&calc_area/1)
                 |> Enum.reduce(0, &(&1 + &2))
    IO.puts "Total area - part 1: #{total_area}"

    total_ribbon = input
                 |> File.read!
                 |> String.split("\n", trim: true)
                 |> Enum.map(&calc_ribbon/1)
                 |> Enum.reduce(0, &(&1 + &2))

    IO.puts "Total ribbon length - part 2: #{total_ribbon}"
  end

  defp calc_area(dim) do
    [h, l, w] = dim
                |> String.split("x")
                |> Enum.map(&String.to_integer/1)
    area_after_side_added = 2 * (h * l + h * w + l * w)
                            |> add_min_side_area([h, l, w])
  end

  defp add_min_side_area(area, [h, l ,w]) do
    area + Enum.min([h*l, h*w, l*w])
  end

  defp calc_ribbon(dim) do
    total_ribbon_length = dim
                          |> String.split("x")
                          |> Enum.map(&String.to_integer/1)
                          |> calc_ribbon_length()
  end

  defp calc_ribbon_length([h, l, w]) do
    least_perimeter = [2 * (h + l), 2 * (h + w), 2 * ( l + w)]
                     |> Enum.min()
    least_perimeter + (h * l * w)
  end
end

I know I can improve the code a lot. I am actually enjoying this. I got to know the Enum library a little bit better because of this and I have to say it’s awesome!!

comments powered by Disqus