Advent of Code 2024
Mix.install([
{:req, "~> 0.3.2"}
])
Day 10
input =
"https://adventofcode.com/2024/day/10/input"
|> Req.get!(headers: [cookie: "session=#{System.get_env("AOC_COOKIE")}"])
|> Map.get(:body)
sample =
"""
89010123
78121874
87430965
96549874
45678903
32019012
01329801
10456732
"""
defmodule Day10 do
def parse(input) do
lines =
input
|> String.split("\n", trim: true)
|> Enum.map(&String.split(&1, "", trim: true))
for {row, y} <- Enum.with_index(lines),
{val, x} <- Enum.with_index(row),
into: %{},
do: {{x, y}, val |> String.to_integer()}
end
def walk_trails(grid) do
grid
|> Enum.reduce([], fn
{pos, 0}, acc -> [pos | acc]
_, acc -> acc
end)
|> Enum.map(&walk_trail(grid, [[&1]], 0))
end
def walk_trail(_grid, [], _), do: 0
def walk_trail(_grid, open, 9), do: open
def walk_trail(grid, open, n) do
open =
open
|> Enum.flat_map(fn [{x, y} | _rest] = path ->
[
{1, 0},
{-1, 0},
{0, 1},
{0, -1}
]
|> Enum.map(fn {dx, dy} -> {x + dx, y + dy} end)
|> Enum.filter(&(Map.get(grid, &1) == n + 1))
|> Enum.map(fn next_pos -> [next_pos | path] end)
end)
walk_trail(grid, open, n + 1)
end
end
import Day10
Part 1
input
|> parse()
|> walk_trails()
|> Enum.map(fn paths ->
paths
|> Enum.map(&hd/1)
|> Enum.uniq()
|> Enum.count()
end)
|> Enum.sum()
Part 2
input
|> parse()
|> walk_trails()
|> Enum.map(&Enum.count/1)
|> Enum.sum()