Skip to content

Instantly share code, notes, and snippets.

@egze
Last active December 7, 2018 16:07
Show Gist options
  • Save egze/217b741254be537543d60ed84423e75c to your computer and use it in GitHub Desktop.
Save egze/217b741254be537543d60ed84423e75c to your computer and use it in GitHub Desktop.
AoC Day5 solution
defmodule Polymer do
defstruct data: []
def new do
%Polymer{}
end
def size(%Polymer{data: data}) do
data |> Enum.count()
end
defimpl Collectable do
def into(%Polymer{data: data}) do
collector_fun = fn
[] = data, {:cont, elem} ->
[elem | data]
[last | rest] = data, {:cont, elem} ->
cond do
elem == last -> [elem | data]
elem != last && String.capitalize(elem) == String.capitalize(last) -> rest
true -> [elem | data]
end
data, :done ->
%Polymer{data: data}
_, :halt ->
:ok
end
{data, collector_fun}
end
end
end
defmodule Day5 do
def part1 do
[line | _rest] = File.read!("input.txt") |> String.split("\n", trim: true)
line
|> String.split("", trim: true)
|> compute_polymer
end
def part2 do
[line | _rest] = File.read!("input.txt") |> String.split("\n", trim: true)
polymer =
line
|> String.split("", trim: true)
|> generate_clean_lists
|> Enum.min_by(fn polymer ->
Polymer.size(polymer)
end)
Polymer.size(polymer)
end
@doc """
Computes the final polymer size
iex> Day5.compute_polymer(["a", "b", "B", "c", "D", "d", "a"])
3
"""
def compute_polymer(chars) do
polymer = for char <- chars, do: char, into: Polymer.new()
Polymer.size(polymer)
end
def generate_clean_lists(chars) do
Enum.map(?a..?z, fn x -> <<x::utf8>> end)
|> Enum.map(fn char ->
clean_chars =
Enum.reject(chars, fn x ->
String.capitalize(x) == String.capitalize(char)
end)
for char <- clean_chars, do: char, into: Polymer.new()
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment