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

Advent of Code 2024 - Day 5

2024/day-05.livemd

Advent of Code 2024 - Day 5

Mix.install([
  {:kino_aoc, "~> 0.1.7"},
  {:libgraph, "~> 0.16.0"}
])

Preparation

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2024", "5", System.fetch_env!("LB_AOC_SESSION"))
[section1, section2] = String.split(puzzle_input, "\n\n")
graph =
  section1
  |> String.split(["|", "\n"])
  |> Enum.map(&String.to_integer/1)
  |> Enum.chunk_every(2, 2)
  |> Enum.reduce(Graph.new(type: :directed), fn [a, b], graph ->
    Graph.add_edge(graph, a, b)
  end)
updates =
  section2
  |> String.split("\n")
  |> Enum.map(fn line ->
    line
    |> String.split(",")
    |> Enum.map(&String.to_integer/1)
  end)

Both Parts

updates
|> Enum.map(fn pages ->
  graph
  |> Graph.subgraph(pages)
  |> Graph.topsort()
  |> then(& &1 -- &1 -- pages)
end)
|> Enum.zip(updates)
|> Enum.split_with(fn {sorted, orig} ->
  sorted == orig
end)
|> Tuple.to_list()
|> Enum.map(fn part ->
  part
  |> Enum.map(&elem(&1, 0))
  |> Enum.map(fn ls ->
    mid = div(length(ls), 2)
    Enum.at(ls, mid)
  end)
  |> Enum.sum()
end)