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

Day 3

day3.livemd

Day 3

Section

defmodule Day3 do
  @priorities_lower Map.new(?a..?z, fn c -> {<>, c - ?a + 1} end)
  @priorities_upper Map.new(?A..?Z, fn c -> {<>, c - ?A + 27} end)
  @priorities Map.merge(@priorities_lower, @priorities_upper)

  def part_1(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(fn row ->
      row = String.graphemes(row)
      n = length(row)
      {l, r} = Enum.split(row, div(n, 2))

      [c] =
        l
        |> MapSet.new()
        |> MapSet.intersection(MapSet.new(r))
        |> Enum.to_list()

      @priorities[c]
    end)
    |> Enum.sum()
  end

  def part_2(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(&amp;(&amp;1 |> String.graphemes() |> MapSet.new()))
    |> Enum.chunk_every(3)
    |> Enum.map(fn [elf1, elf2, elf3] ->
      badge = elf1 |> MapSet.intersection(elf2) |> MapSet.intersection(elf3) |> Enum.at(0)
      @priorities[badge]
    end)
    |> Enum.sum()
  end
end
test_input = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
"""

Day3.part_1(test_input)
input = File.read!("day3_input.txt")

Day3.part_1(input)
Day3.part_2(test_input)
Day3.part_2(input)