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

Advent of Code 2023 - Day 05

2023/05.livemd

Advent of Code 2023 - Day 05

Mix.install([
  {:kino, "~> 0.11.0"},
  {:kino_aoc, github: "ljgago/kino_aoc"}
])

Input

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "5", System.fetch_env!("LB_AOC_SESSION"))
[seeds | rest] =
  puzzle_input
  |> String.split(["\n\n", ":"])
  |> Enum.drop_every(2)
  |> Enum.map(fn line ->
    Regex.scan(~r/\d+/, line)
    |> List.flatten()
    |> Enum.map(&String.to_integer/1)
  end)
mappers =
  for raw <- rest do
    Enum.chunk_every(raw, 3)
    |> Enum.map(fn [d1, s1, length] -> {s1..(s1 + length - 1), _diff = s1 - d1} end)
    |> Enum.sort_by(fn {s1.._, _} -> s1 end)
  end

Part 1

closest_destination = fn seed ->
  Enum.reduce(mappers, seed, fn mapper, pos ->
    Enum.find(mapper, {pos..pos, 0}, fn {s, _diff} -> pos in s end)
    |> then(fn {_s, diff} -> pos - diff end)
  end)
end

seeds
|> Stream.map(closest_destination)
|> Enum.min()

Run in Livebook