Skip to content

Instantly share code, notes, and snippets.

@jemmyw
Created December 9, 2018 10:21
Show Gist options
  • Save jemmyw/e3e8e1079e0f265af3c96789bd7ad682 to your computer and use it in GitHub Desktop.
Save jemmyw/e3e8e1079e0f265af3c96789bd7ad682 to your computer and use it in GitHub Desktop.
defmodule Polymer do
def scan(p, status \\ :ok)
def scan(p, _) when is_bitstring(p) do
p = "%#{p}"
p
|> String.to_charlist()
|> scan(:ok)
|> elem(0)
|> to_string
|> String.slice(1..-1)
end
def scan([], s), do: {[], s}
def scan([f | [f | t]], s) do
{nl, ns} = scan([f | t], s)
case ns do
:backtrace -> scan([f | nl], :ok)
_ -> {[f | nl], :ok}
end
end
def scan([f | [n | t]], _) do
fs = [f] |> to_string |> String.upcase()
ns = [n] |> to_string |> String.upcase()
cond do
ns == fs ->
{t, :backtrace}
true ->
{next_list, next_status} = scan([n | t], :ok)
case next_status do
:backtrace ->
scan([f | next_list], :ok)
_ ->
{[f | next_list], :ok}
end
end
end
def scan([f | t], s) do
{[f | t], s}
end
end
polymer = File.read("5.txt") |> elem(1)
# Part 1
polymer |> Polymer.scan() |> String.length() |> IO.inspect()
# Part 2
shortest =
Enum.reduce(?a..?z, nil, fn letter, len ->
next =
Regex.compile([letter] |> to_string, "i")
|> elem(1)
|> Regex.replace(polymer, "")
|> Polymer.scan()
|> String.length()
cond do
len == nil -> next
len > next -> next
true -> len
end
end)
IO.inspect(shortest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment