Day 5: Alchemical Reduction - Advent of Code 2018

I did the Advent of Code 2018 day 5 challenge in Elixir! Parts one and two are as follows:

defmodule Day5 do
  def part1(input) do
    input
    |> read_input()
    |> String.codepoints()
    |> reduce_polymer()
  end

  def part2(input) do
    chars =
      input
      |> read_input()
      |> String.codepoints()

    unit_types =
      chars
      |> Enum.map(&String.downcase/1)
      |> Enum.uniq()

    Enum.reduce(unit_types, 1_000_000, fn unit_type, min_size ->
      without_unit =
        Enum.reject(chars, fn char ->
          String.downcase(char) == unit_type
        end)

      min(min_size, reduce_polymer(without_unit))
    end)
  end

  defp read_input(input) do
    input
    |> File.read!()
    |> String.trim()
  end

  defp reduce_polymer(chars) do
    Enum.reduce(chars, [], fn
      char, [] ->
        [char]

      char, [last_seen | rest] = acc ->
        result =
          if char != last_seen &&
               (char == String.upcase(last_seen) || char == String.downcase(last_seen)) do
            rest
          else
            [char | acc]
          end

        result
    end)
    |> length()
  end
end

# :aoc2018 |> :code.priv_dir() |> Path.join("day5.txt") |> Day5.part1()
# :aoc2018 |> :code.priv_dir() |> Path.join("day5.txt") |> Day5.part2()

# input = "dabAcCaCBAcCcaDA"
# r Day5; Day5.part2(input)

 

Author

Simon Escobar Benitez

Colombian Software Engineer (Erlang Solutions)

Upcoming conferences

Start booking your calendar with more Code Sync conferences happening across the globe. We will be slowly releasing more dates, in the meantime here is what we’ve planned already:

All conferences

ARTICLES: 8

Day 11: Chronal Charge - Advent of Code 2018

I did the Advent of Code 2018 day 11 challenge in Elixir! Parts one and two are as follows:

READ MORE

Day 10: The Stars Align - Advent of Code 2018

I did the Advent of Code 2018 day 10 challenge in Elixir! Parts one and two are as follows:

READ MORE

Day 7: The Sum of Its Parts - Advent of Code 2018

I did the Advent of Code 2018 day 7 challenge in Elixir! Parts one and two are as follows:

READ MORE

Day 6: Chronal Coordinates - Advent of Code 2018

I did the Advent of Code 2018 day 6 challenge in Elixir! Parts one and two are as follows:

READ MORE

Day 4: Repose Record - Advent of Code 2018

I did the Advent of Code 2018 day 4 challenge in Elixir! Parts one and two are as follows:

READ MORE

Day 3: No matter how you slice it - Advent of Code 2018

I did the Advent of Code 2018 day 3 challenge in Elixir! Parts one and two are as follows:

READ MORE

Day 2: Inventory Management System - Advent of Code 2018

I did the Advent of Code 2018 day 2 challenge in Elixir! Parts one and two are as follows:

READ MORE

Day 1: Chronal Calibration - Advent of Code 2018

Advent of Code 2018 - Day 1 solution in Elixir! #AdventOfBEAM

READ MORE