Advent of Code 2023 Day 14
Mix.install([
{:kino_aoc, "~> 0.1.5"}
])
Prep
{:ok, puzzle_input} =
KinoAOC.download_puzzle("2023", "14", System.fetch_env!("LB_AOC_SESSION"))
IO.puts(puzzle_input)
dish =
puzzle_input
|> String.split("\n")
|> Enum.map(&String.to_charlist/1)
|> Enum.map(fn line ->
Enum.map(line, fn
?O -> 1
?. -> 0
?# -> 0.0
end)
end)
rotate = fn dish ->
dish
|> Enum.reverse()
|> Enum.zip_with(&Function.identity/1)
end
tilt = fn dish ->
dish
|> Enum.map(fn line ->
line
|> Stream.chunk_by(&is_integer/1)
|> Enum.map(&Enum.sort/1)
|> List.flatten()
end)
end
load = fn dish ->
dish
|> Stream.map(fn line ->
line
|> Stream.with_index(1)
|> Stream.map(&Tuple.product/1)
|> Enum.sum()
end)
|> Enum.sum()
|> trunc()
end
dish = rotate.(dish)
Part 1
dish |> tilt.() |> load.()
Part 2
cycle = fn dish ->
dish
|> tilt.()
|> rotate.()
|> tilt.()
|> rotate.()
|> tilt.()
|> rotate.()
|> tilt.()
|> rotate.()
end
0 -> 1 -> 3 -> 4 -> 5
^ |
| v
8 <- 7 <- 6
before_enter_loop =
{dish, MapSet.new()}
|> Stream.iterate(fn {dish, seen} ->
{cycle.(dish), MapSet.put(seen, dish)}
end)
|> Enum.find_index(fn {dish, seen} -> dish in seen end)
loop_length =
dish
|> Stream.iterate(cycle)
|> Stream.drop(before_enter_loop)
|> Enum.reduce_while(MapSet.new(), fn dish, seen ->
if dish in seen do
{:halt, seen}
else
{:cont, MapSet.put(seen, dish)}
end
end)
|> MapSet.size()
remainder = rem(1_000_000_000 - before_enter_loop + loop_length, loop_length)
dish
|> Stream.iterate(cycle)
|> Enum.at(before_enter_loop - loop_length + remainder)
|> load.()