bjorng

bjorng

Erlang Core Team

Advent of Code 2021 - Day 10

This topic is about Day 10 of the Advent of Code 2021.

We have a private leaderboard (shared with users of Erlang Forums ):

https://adventofcode.com/2021/leaderboard/private/view/370884

The entry code is:
370884-a6a71927

Most Liked

ruslandoga

ruslandoga

I used a bit of metaprogramming to define the line processor that worked on binaries:

defp process_line(line) do
  process_line(line, _stack = [])
end

for <<open, close>> <- ["[]", "()", "{}", "<>"] do
  defp process_line(<<unquote(close), rest::bytes>>, [unquote(close) | stack]) do
    process_line(rest, stack)
  end

  defp process_line(<<unquote(open), rest::bytes>>, stack) do
    process_line(rest, [unquote(close) | stack])
  end
end

defp process_line(<<>>, []), do: :valid
defp process_line(<<>>, stack), do: {:incomplete, stack}
defp process_line(<<char, _rest::bytes>>, _stack), do: {:corrupted, char}

Full solution

mexicat

mexicat

Today’s problem seemed like a good match for Elixir.

defmodule AdventOfCode.Day10 do
  @chunks %{
    "(" => ")",
    "[" => "]",
    "{" => "}",
    "<" => ">"
  }

  def part1(input) do
    input
    |> parse_input()
    |> Enum.map(&eval_line/1)
    |> Enum.filter(&(elem(&1, 0) == :error))
    |> Enum.map(fn {_, v} -> v end)
    |> Enum.sum()
  end

  def part2(input) do
    results =
      input
      |> parse_input()
      |> Enum.map(&eval_line/1)
      |> Enum.filter(&(elem(&1, 0) == :ok))
      |> Enum.map(fn {_, v} -> v end)
      |> Enum.sort()

    middle = results |> length() |> div(2)
    Enum.at(results, middle)
  end

  def eval_line(line, open \\ [])

  def eval_line([head | tail], open) when head in ["(", "[", "{", "<"] do
    eval_line(tail, [head | open])
  end

  def eval_line([head | tail], [open_head | open_tail]) do
    if head == @chunks[open_head] do
      eval_line(tail, open_tail)
    else
      {:error, score_error(head)}
    end
  end

  def eval_line(_, open) do
    score =
      Enum.reduce(open, 0, fn char, acc ->
        acc * 5 + score_ac(@chunks[char])
      end)

    {:ok, score}
  end

  def score_error(")"), do: 3
  def score_error("]"), do: 57
  def score_error("}"), do: 1197
  def score_error(">"), do: 25137

  def score_ac(")"), do: 1
  def score_ac("]"), do: 2
  def score_ac("}"), do: 3
  def score_ac(">"), do: 4

  def parse_input(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(&String.codepoints/1)
  end
end
ruslandoga

ruslandoga

I think it is equivalent except that my implementation for part2 needs to be updated to score openers instead of closers (since stack contains openers for incomplete lines). I rerun the tests with these two changes and they passed.

As for your original question,

Any reason it is better to match on insertion into the stack rather than on popping off the stack?

I don’t think I had any particular reason, at the moment it just made sense to add closers to the stack.

Where Next?

Popular in Challenges Top

Aetherus
Hello, guys. I’m back again, but only for the weekends, maybe. This topic is about Day 13 of the Advent of Code 2020 . Thanks to @egze,...
New
sb8244
Note: This topic is to talk about Day 10 of the Advent of Code 2019 . There is a private leaderboard for elixirforum members. You can jo...
New
kwando
Phew, this one took a while to get right. My naive attempts was way to slow so I reached for Dijkstras shortest path algorithm.. and that...
New
bjorng
This topic is about Day 18 of the Advent of Code 2021. We have a private leaderboard (shared with users of Erlang Forums): https://adve...
New
Qqwy
Note by the Moderators: This topic is to talk about Day 6 of the Advent of Code. For general discussion about the Advent of Code 2018 an...
New
shritesh
This was way too easy after the last few days. Simple map, filter and count. https://github.com/shritesh/advent/blob/main/2023/06.livemd
New
bjorng
Note: This topic is to talk about Day 5 of the Advent of Code 2019. There is a private leaderboard for elixirforum members. You can join...
New
adamu
Nobody’s doing Advent of Code this year? :grinning_face_with_smiling_eyes: I might do the first week or so. For Day 1, first I solved i...
New
connorlay
Note by the Moderators: This topic is for general discussion about the Advent of Code 2018. To prevent people from being spoiled about s...
New
maennchen
Ok, that was a rough one today. I haven’t found a way to improve the algorithm further. Part 1 runs in .5 seconds, Part 2 in ~ 5 minutes...
New

Other popular topics Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52673 488
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 127089 1222
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New

We're in Beta

About us Mission Statement