Skip to content

Instantly share code, notes, and snippets.

@joeesteves
Created December 6, 2018 13:54
Show Gist options
  • Save joeesteves/b801ce258dc0959b71948bceb4e29a85 to your computer and use it in GitHub Desktop.
Save joeesteves/b801ce258dc0959b71948bceb4e29a85 to your computer and use it in GitHub Desktop.
defmodule Day5 do
@doc """
Removes adjacents when they have opposite polarity (determined by case Aa), it recurses over result until there are no further adyacent oposites
iex> Day5.slice_polarity_matches("dabAcCaCBAcCcaDA", "")
"dabCBAcaDA"
"""
def slice_polarity_matches(string, prev_string) when is_binary(prev_string) do
cond do
String.length(string) == String.length(prev_string) ->
string
true ->
process_string(string)
|> slice_polarity_matches(:second_pass)
|> slice_polarity_matches(string)
end
end
def slice_polarity_matches(string, :second_pass) do
{first_char, rest } = String.split_at(string, 1)
first_char <> process_string(rest)
end
defp process_string(string) do
String.to_charlist(string)
|> Enum.chunk_every(2)
|> Enum.filter(&are_compatible/1)
|> Enum.flat_map(&(&1))
|> List.to_string
end
defp are_compatible([left, right]) do
abs(left - right) != 32
end
defp are_compatible(_) do
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment