about summary refs log tree commit diff
path: root/day5.exs
blob: 120f185cf5f27cdc9fe4ec0c997014f95e341b18 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
defmodule Day5 do
  def input() do
    File.stream!("input/day5.in")
    |> Stream.map(&String.trim/1)
    |> Enum.at(0)
  end

  def part1() do
    input()
    |> String.graphemes()
    |> react()
    |> Enum.count()
  end

  def part2() do
    for(n <- ?a..?z, do: <<n::utf8>>)
    |> Enum.map(fn c ->
      input()
      |> String.replace(c, "")
      |> String.replace(String.upcase(c), "")
      |> String.graphemes()
      |> react()
    end)
    |> Enum.min_by(&Enum.count/1)
    |> Enum.count()
  end

  def react(polymer) do
    Enum.reduce(polymer, [], fn
      x, [] ->
        [x]

      x, [y] ->
        [x, y]

      x, [y | ys] ->
        if x != y && String.downcase(x) == String.downcase(y) do
          ys
        else
          [x, y | ys]
        end
    end)
  end
end

IO.puts(Day5.part1())
IO.puts(Day5.part2())