seeplusplus

seeplusplus

Advent of Code 2024 - Day 10

This one wasn’t too bad :slight_smile: I actually ended up solving part 2 first, and had to work around it in part 1 to get the answer there!

input = ""
|> String.trim()
tiles = input |> String.split("\n")
  |> Stream.with_index() 
  |> Enum.flat_map(fn {line, l_idx} ->
    line 
    |> String.trim() 
    |> String.graphemes()
    |> Stream.with_index()
    |> Enum.map(fn {".", idx} -> {{idx, l_idx}, nil}
      {c, idx} -> {{idx, l_idx}, c |> String.to_integer()} end)
end)
|> Enum.into(Map.new())
grid = Grid2D.new(
  input |> String.split("\n") |> Enum.at(0) |> String.trim() |> String.length(),
  input |> String.trim() |> String.split("\n") |> Enum.count()
)
defmodule TrailFinder do
  def find_trails(input, tiles, grid) do
    tiles
    |> Stream.filter(fn {_, v} -> v == 0 end)
    |> Enum.map(fn {k, _} -> {k, find_trails(input, tiles, grid, k, 0, [])} end)
  end
  def find_trails(_, _, _, p, 9, acc), do: [[{p, 9} | acc]]
  def find_trails(input, tiles, grid, start, height, acc) do
    Grid2D.neighbors(start, grid, :straight)
    |> Enum.filter(fn p -> Map.get(tiles, p) == height + 1 end)
    |> Enum.flat_map(fn p ->
        find_trails(input, tiles, grid, p, height + 1, [{start, height} | acc])
    end)
  end
end
TrailFinder.find_trails(input, tiles, grid)
|> Enum.map(fn {s, l} -> {s, for [peak |_] <- l, into: MapSet.new do peak end } end)
|> Enum.map(fn {_, s} -> MapSet.size(s) end)
|> Enum.sum()
TrailFinder.find_trails(input, tiles, grid)
|> Stream.map(fn {_, l} -> l |> Enum.count end)
|> Enum.sum()

Most Liked

rugyoga

rugyoga

Same!
I accidentally solved part 2 first and then fixed it to run part1. lol

rySeeR

rySeeR

After having the most inefficient code yesterday that took almost 40 minutes to run hahaha, I’m surprised that today tooks 2ms to run, at the first try.

Also solved both at the same time.

I think it might be time to build a custom grid module…

Aetherus

Aetherus

Solved Part 2 first, too. Here’s my code using dynamic programming (not very FP, though):

defmodule AoC2024.Day10 do
  @type grid() :: %{coord() => 0..9}
  @type coord() :: {i::non_neg_integer(), j::non_neg_integer()}

  @spec part_1(grid()) :: non_neg_integer()
  def part_1(grid) do
    Task.async(fn ->
      grid
      |> Enum.filter(&elem(&1, 1) == 0)
      |> Enum.map(&elem(&1, 0))
      |> Enum.map(&dp_1(grid, &1))
      |> Enum.map(&length/1)
      |> Enum.sum()
    end)
    |> Task.await(:infinity)
  end

  @spec part_2(grid()) :: non_neg_integer()
  def part_2(grid) do
    Task.async(fn ->
      grid
      |> Enum.filter(&elem(&1, 1) == 0)
      |> Enum.map(&elem(&1, 0))
      |> Enum.map(&dp_2(grid, &1))
      |> Enum.sum()
    end)
    |> Task.await(:infinity)
  end

  defp dp_1(grid, {i, j}) do
    case grid[{i, j}] do
      9 ->
        [{i, j}]

      n ->
        memoized({i, j}, fn ->
          [{i - 1, j}, {i + 1, j}, {i, j - 1}, {i, j + 1}]
          |> Enum.filter(&grid[&1] == n + 1)
          |> Enum.flat_map(&dp_1(grid, &1))
          |> Enum.uniq()
        end)
    end
  end

  defp dp_2(grid, {i, j}) do
    case grid[{i, j}] do
      9 ->
        1

      n ->
        memoized({i, j}, fn ->
          [{i - 1, j}, {i + 1, j}, {i, j - 1}, {i, j + 1}]
          |> Enum.filter(&grid[&1] == n + 1)
          |> Enum.map(&dp_2(grid, &1))
          |> Enum.sum()
        end)
    end
  end

  defp memoized(key, fun) do
    with nil <- Process.get(key) do
      fun.() |> tap(&Process.put(key, &1))
    end
  end
end

Benchmark (without the parsing part)

Name             ips        average  deviation         median         99th %
part_2        508.15        1.97 ms     ±3.72%        1.96 ms        2.04 ms
part_1        409.82        2.44 ms     ±1.00%        2.44 ms        2.53 ms
bjorng

bjorng

Erlang Core Team

And I also solved part 2 first.

sevenseacat

sevenseacat

Author of Ash Framework

Is this the first time I’ve cranked out the graphs for 2024? I think it is…

Part 2 was trivial after implementing part 1. I like when that happens.

Name                     ips        average  deviation         median         99th %
day 10, part 1          3.87      258.13 ms     ±0.90%      258.51 ms      263.14 ms
day 10, part 2          4.19      238.57 ms     ±0.55%      238.51 ms      241.13 ms

Where Next?

Popular in Challenges Top

JEG2
Note: This topic is to talk about Day 9 of the Advent of Code. For general discussion about the Advent of Code 2018 and links to topics ...
New
antoine-duchenet
Everything went smoothly today. Nothing to change to solve part 2 because I already used memoization for part 1 (it looked like an AoC e...
New
sneako
Note by the Moderators: This topic is to talk about the first day of the Advent of Code. For general discussion about the Advent of Code...
New
DmitriyChernyavskiy
Hello everyone, I’m a new in elexir and functional language. I’m trying to implement Websocket interraction with server. On first layer...
New
lud
At first I was scared but I found is a simple way to compute the sides. defmodule AdventOfCode.Solutions.Y24.Day12 do alias AdventOfCo...
New
bjorng
Note: This topic is to talk about Day 12 of the Advent of Code 2019. There is a private leaderboard for elixirforum members. You can joi...
New
igorb
I found today a bit tedious: advent-of-code-2024/lib/advent_of_code2024/day15.ex at main · ibarakaiev/advent-of-code-2024 · GitHub.
New
bjorng
My solution finishes both parts in 5 seconds on my computer. That time should be possible to reduce by optimizing my rather naive tilt/2 ...
New
code-shoily
Just did part 1. Part 2 seems to be demanding too much of my reading time so will get to that after I am done with some chores. Oh here ...
New
bjorng
This topic is about Day 10 of the Advent of Code 2021. We have a private leaderboard (shared with users of Erlang Forums ): https://adv...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement