Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

aoc2021 day10

2021/elixir/day-10.livemd

aoc2021 day10

Setup

Mix.install([{:kino, "~> 0.4.1"}])
input = Kino.Input.textarea("input")

Part1

inputs = """
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
"""

complete? = fn
  ?(, ?) ->
    true

  ?{, ?} ->
    true

  ?[, ?] ->
    true

  ?<, ?> ->
    true

  _, _ ->
    false
end

score_map = %{
  ?) => 3,
  ?] => 57,
  ?} => 1197,
  ?> => 25137
}

input
|> Kino.Input.read()
|> String.split("\n", trim: true)
|> Enum.map(&amp;String.to_charlist/1)
|> Enum.map(fn line ->
  line
  |> Enum.reduce_while([], fn
    c, st when c in '[({<' ->
      {:cont, [c | st]}

    c, [] ->
      {:halt, c}

    c, st ->
      if complete?.(hd(st), c) do
        {:cont, tl(st)}
      else
        {:halt, c}
      end
  end)
end)
|> Enum.reject(&amp;is_list/1)
|> Enum.map(&amp;score_map[&amp;1])
|> Enum.sum()

Part 2

complete? = fn
  ?(, ?) ->
    true

  ?{, ?} ->
    true

  ?[, ?] ->
    true

  ?<, ?> ->
    true

  _, _ ->
    false
end

score_map = %{
  ?( => 1,
  ?[ => 2,
  ?{ => 3,
  ?< => 4
}

input
|> Kino.Input.read()
|> String.split("\n", trim: true)
|> Enum.map(&amp;String.to_charlist/1)
|> Enum.map(fn line ->
  line
  |> Enum.reduce_while([], fn
    c, st when c in '[({<' ->
      {:cont, [c | st]}

    c, [] ->
      {:halt, c}

    c, st ->
      if complete?.(hd(st), c) do
        {:cont, tl(st)}
      else
        {:halt, c}
      end
  end)
end)
|> Enum.filter(&amp;is_list/1)
|> Enum.map(fn heads ->
  Enum.reduce(heads, 0, fn h, score ->
    score * 5 + score_map[h]
  end)
end)
|> Enum.sort()
|> then(&amp;Enum.at(&amp;1, div(length(&amp;1), 2)))