Commit 9e7a7640 authored by Nikolay Petrachkov's avatar Nikolay Petrachkov

Add Advent_of_code_2018#Day_05 part 2 in Elixir

parent 32ee0394
defmodule Polymer do
@moduledoc """
Removes units with opposite polarization
(sequence of letters with opposite capitalizetion).
(sequence of letters with opposite capitalization).
"""
def start(filename) do
def start1(filename) do
filename
|> File.stream!()
|> Stream.flat_map(&String.split(&1, "\n", trim: true))
|> Stream.flat_map(&String.to_charlist/1)
|> Stream.chunk_every(5000)
|> prepare_input
|> do_reaction
end
def start2(filename) do
input = filename |> prepare_input
units = input |> Enum.reduce(%{}, fn ch, acc ->
if ch in ?a..?z do
Map.put(acc, ch, 0)
else acc
end
end)
units
|> Map.keys()
|> Task.async_stream(&react(&1, input), [timeout: 1000000, max_concurrency: 4])
|> Enum.reduce(%{}, fn {:ok, {v, c}}, acc -> Map.put(acc, v, c) end)
|> Map.values
|> Enum.min
end
def react(v, input) do
v
|> stream_filter(input)
|> do_reaction
|> create_tuple(v)
end
def do_reaction(value) do
value
|> Stream.chunk_every(1000)
|> Task.async_stream(&Polymer.compute/1)
|> Enum.reduce([], fn {:ok, part}, acc -> acc ++ [part] end)
|> List.to_string()
......@@ -18,6 +46,21 @@ defmodule Polymer do
|> Enum.count()
end
def create_tuple(count, v) do
{v, count}
end
def stream_filter(value, st) do
Stream.filter(st, fn x -> x not in [value, value - 32] end)
end
def prepare_input(filename) do
filename
|> File.stream!()
|> Stream.flat_map(&String.split(&1, "\n", trim: true))
|> Stream.flat_map(&String.to_charlist/1)
end
def compute([h | t]), do: compute(t, h, [])
def compute([h | []], Nil, seen), do: compute([], Nil, seen ++ [h])
def compute([h | t], Nil, seen), do: compute(t, h, seen)
......
......@@ -2,6 +2,18 @@ defmodule PolymerTest do
use ExUnit.Case
test "computes polymer" do
assert Polymer.start("test/test.txt") == "dabCBAcaDA"
assert Polymer.start1("test/test.txt") == 10
end
# test "computes final polymer" do
# assert Polymer.start1("data.txt") == 10250
# end
test "computes shortest polymer" do
assert Polymer.start2("test/test2.txt") == 4
end
# test "computes final shortest polymer" do
# assert Polymer.start2("data.txt") == 6188
# end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment