cblavier

cblavier

Advent of Code 2020 - Day 11

Hey there :wave:

CleanShot 2020-12-11 at 10.59.25@2x

No magic or algorithmic finesse today, I just finished the challenge and I my code is quite slow (1sec for part1, 3sec for part2).

But at least I managed to made my code readable and to reuse most of part1 for part2.

My code: part1 / part2

Most Liked

LostKobrakai

LostKobrakai

Recursion if it’s truely while do or do while:

My other goto for evaluation (does not always fit) is Stream.unfold:

cblavier

cblavier

I ended up writing a generator to create my adventofcode files for each challenge and to download the puzzle as well. You can use the code if you want to

Papey

Papey

I ended up with something nice for finding neighbours on part 2, but wow, this is veeeerryyyy slooooow (~4 seconds)

  def neighbours(current, {x, y}) do
    Enum.reduce(@dirs, 0, fn {dx, dy}, acc ->
      [v] =
        Stream.iterate(1, &(&1 + 1))
        |> Stream.map(fn mul -> {x + dx * mul, y + dy * mul} end)
        |> Stream.map(fn {xx, yy} -> Map.get(current, {xx, yy}) end)
        |> Stream.drop_while(&(&1 == @floor))
        |> Enum.take(1)

      if v == @occupied, do: acc + 1, else: acc
    end)
  end

I was thinking about the fact that the current map is RO, did someone try to add some concurrency into the mix ?

felix-alonso

felix-alonso

I think I had a similar experience today. Worked out okay, but a bit slower than I would like (~1s/~3s).

defmodule Day11 do

  defguard in_bounds(x, list) when 0 <= x and x < length(list)

  def part_1, do: solve(&by_adjacency/4)
  def part_2, do: solve(&by_visibility/4)

  def solve(method) do
    load()
    |> find_stable(method)
    |> count_occupied()
  end

  def count_occupied(seats) do
    seats
    |> Enum.map(fn row -> Enum.count(row, &(&1 == ?#)) end)
    |> Enum.sum()
  end

  def find_stable(seats, transform) do
    case next_gen(seats, transform) do
      next when next == seats -> next
      next -> find_stable(next, transform)
    end
  end

  def next_gen(seats, transform) do
    for {row, r_idx} <- Enum.with_index(seats) do
      for {seat, c_idx} <- Enum.with_index(row) do
        transform.(seats, seat, r_idx, c_idx)
      end
    end
  end

  def by_visibility(_, ?., _, _), do: ?.
  def by_visibility(seats, ?L, row, col) do
    if visible(seats, row, col) == 0, do: ?#, else: ?L
  end
  def by_visibility(seats, ?#, row, col) do
      if visible(seats, row, col) >= 5, do: ?L, else: ?#
  end

  def visible(seats, r_idx, c_idx) do
    directions()
    |> Enum.count(fn {x, y} -> next(seats, r_idx + x, c_idx + y, x, y) end)
  end

  def next(_, row, col, _, _) when row < 0 or col < 0, do: false
  def next(seats, row, col, drow, dcol) do
    case get_seat(seats, row, col) do
      ?. -> next(seats, row + drow, col + dcol, drow, dcol)
      x -> x == ?#
    end
  end

  def by_adjacency(_, ?., _, _), do: ?.
  def by_adjacency(seats, ?L, row, col) do
    if adjacent(seats, row, col) == 0, do: ?#, else: ?L
  end
  def by_adjacency(seats, ?#, row, col) do
      if adjacent(seats, row, col) >= 4, do: ?L, else: ?#
  end

  def adjacent(seats, row, col) do
    directions()
    |> Enum.count(fn {x, y} -> get_seat(seats, row + x, col + y) == ?#  end)
  end

  def directions do
    for x <- -1..1, y <- -1..1, not_origin(x, y), do: {x, y}
  end

  def not_origin(x, y), do: not(x == 0 and y == 0)

  def get_seat(seats=[fst|_], row, col)
    when in_bounds(row, seats) and in_bounds(col, fst),
    do: seats |> Enum.at(row) |> Enum.at(col) 
  def get_seat(_, _, _), do: nil

  def load do
    File.read!("day-11.input")
    |> String.split("\n", trim: true)
    |> Enum.map(&String.to_charlist/1)
  end
end

Code on github

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