Powered by AppSignal & Oban Pro

Day 3: Rucksack Reorganization

2022/day_03.livemd

Day 3: Rucksack Reorganization

Mix.install([:kino])

input = Kino.Input.textarea("Please paste your input:")

Part 1

Run in Livebook

https://adventofcode.com/2022/day/3

data =
  input
  |> Kino.Input.read()
  |> String.split("\n", trim: true)
priorities = Enum.zip(?a..?z, 1..26) ++ Enum.zip(?A..?Z, 27..52)

get_priority = fn item ->
  priorities
  |> Enum.find_value(fn
    {^item, priority} -> priority
    _ -> nil
  end)
end

_answer1 =
  data
  |> Enum.map(fn str ->
    length = str |> String.length()

    str |> String.split_at(div(length, 2))
  end)
  |> Enum.map(fn {compartment1, compartment2} ->
    mapset =
      compartment1
      |> String.to_charlist()
      |> MapSet.new()

    compartment2
    |> String.to_charlist()
    |> Enum.find(&MapSet.member?(mapset, &1))
    |> get_priority.()
  end)
  |> Enum.sum()

Part 2

https://adventofcode.com/2022/day/3#part2

_answer2 =
  data
  |> Enum.chunk_every(3)
  |> Enum.map(fn group ->
    [badge] =
      group
      |> Enum.map(fn items ->
        items
        |> String.to_charlist()
        |> MapSet.new()
      end)
      |> Enum.reduce(&MapSet.intersection(&1, &2))
      |> MapSet.to_list()

    get_priority.(badge)
  end)
  |> Enum.sum()