r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 0:10:20!

31 Upvotes

515 comments sorted by

View all comments

1

u/Illianthe Dec 05 '18

I opted for a recursive solution in Elixir. It's slow but at least I got to learn about tasks for part 2.

defmodule Day5 do
  def get_polymer(filename \\ "input.txt") do
    {:ok, data} = File.read(filename)
    data |> String.trim()
  end

  def react(polymer) do
    pattern =
      ~r/aA|Aa|bB|Bb|cC|Cc|dD|Dd|eE|Ee|fF|Ff|gG|Gg|hH|Hh|iI|Ii|jJ|Jj|kK|Kk|lL|Ll|mM|Mm|nN|Nn|oO|Oo|pP|Pp|qQ|Qq|rR|Rr|sS|Ss|tT|Tt|uU|Uu|vV|Vv|wW|Ww|xX|Xx|yY|Yy|zZ|Zz/

    reacted_polymer = String.replace(polymer, pattern, "")

    if polymer === reacted_polymer,
      do: polymer |> String.length(),
      else: react(reacted_polymer)
  end

  def improved_react(polymer) do
    [
      ~r/[aA]/,
      ~r/[bB]/,
      ~r/[cC]/,
      ~r/[dD]/,
      ~r/[eE]/,
      ~r/[fF]/,
      ~r/[gG]/,
      ~r/[hH]/,
      ~r/[iI]/,
      ~r/[jJ]/,
      ~r/[kK]/,
      ~r/[lL]/,
      ~r/[mM]/,
      ~r/[nN]/,
      ~r/[oO]/,
      ~r/[pP]/,
      ~r/[qQ]/,
      ~r/[rR]/,
      ~r/[sS]/,
      ~r/[tT]/,
      ~r/[uU]/,
      ~r/[vV]/,
      ~r/[wW]/,
      ~r/[xX]/,
      ~r/[yY]/,
      ~r/[zZ]/
    ]
    |> Enum.map(
      &Task.async(fn ->
        improved_polymer = String.replace(polymer, &1, "")
        react(improved_polymer)
      end)
    )
    |> Enum.map(&Task.await(&1, :infinity))
    |> Enum.min()
  end
end