jkwchui

jkwchui

Advent of Code 2022 - Day 11

Monkeys fitted squarely as GenServers in my head. My initial problem was using cast instead of call; I imagine impolite monkeys slinging bananas at each other as fast as they can. (At the end I’m still not sure whether this {:global, ".."}) naming strategy is idiomatic.)

For part 2, I hard-coded the @monkey_factor to assuage my worry level, and then it is otherwise exactly the same as part 1. There must be some less literal way of going about this, so I’m looking forward to seeing other solutions!

Main module

defmodule Day11Monkeys do
@moduledoc “”"
Documentation for Day11Monkeys.
“”"

  def part_2(input \\ "test") do
    notes =
      input
      |> load_notes()
      |> Enum.map(&parse_note/1)

    monkeys =
      for note <- notes do
        monkey_name = note[:monkey] |> Integer.to_string()
        {:ok, _pid} = Monkey.start_link(note, {:global, monkey_name})
        monkey_name
      end

    # simulate rounds
    for round <- 1..10_000 do
      IO.inspect "round #{round}"
      for monkey <- monkeys do
        for _item <- Monkey.get_items(monkey) do
          Monkey.inspect_item(monkey)
        end
      end
    end

    [top, second] =
      for monkey <- monkeys do
        Monkey.get_inspections(monkey)
      end
      |> Enum.sort(:desc)
      |> Enum.slice(0..1)

    top * second
  end

  def data_path(input), do:
    Path.expand "./priv/#{input}.txt"

  def load_notes(input) do
    input
    |> data_path()
    |> File.stream!()
    |> Stream.map(&String.trim/1)
    |> Enum.chunk_every(7)
    |> Enum.map(fn lines ->
        if lines |> Enum.at(-1) == "" do
          Enum.drop(lines, -1)
        else
          lines
        end
      end)
  end

  def parse_note(raw_note) do
    [
      "Monkey " <> monkey,
      "Starting items:" <> items,
      "Operation: new = old " <> operation,
      "Test: divisible by " <> test,
      "If true: throw to monkey " <> true_throw,
      "If false: throw to monkey " <> false_throw
    ] = raw_note

    %{
      monkey: monkey |> String.slice(0..-2) |> String.to_integer(),
      items: items
              |> String.split(",")
              |> Enum.map(fn item ->
                item |> String.trim() |> String.to_integer
              end),
      operation: to_function(operation),
      test_divisibility: test |> String.to_integer,
      throw_if_true: true_throw,
      throw_if_false: false_throw,
      inspections: 0
    }
  end

  def to_function("+" <> num_as_string) do
    number = num_as_string |> String.trim() |> String.to_integer()

    fn value -> (value + number) end
  end
  def to_function("* old") do
    fn value -> (value * value) end
  end
  def to_function("*" <> num_as_string) do
    number = num_as_string |> String.trim() |> String.to_integer()

    fn value -> (value * number) end
  end

end
Monkey GenServer
defmodule Monkey do
  use GenServer

  @monkey_factor 17 * 5 * 11 * 13 * 3 * 19 * 2 * 7
  # Sample monkey:
  # [
  #   %{
  #     items: [54, 65, 75, 74],
  #     monkey: 1,
  #     operation: #Function<3.79865354/1 in Day11Monkeys.to_function/1>,
  #     test_divisibility: 19,
  #     throw_if_false: 0,
  #     throw_if_true: 2
  #   }
  # ]

  # CLIENT
  def start_link(monkey, name \\ __MODULE__) do
    # you may want to register your server with `name: __MODULE__`
    # as a third argument to `start_link`
    GenServer.start_link(__MODULE__, monkey, name: name)
  end

  def get_state(server), do:
    GenServer.call({:global, server}, :state)

  def get_items(server), do:
    GenServer.call({:global, server}, :items)

  def get_inspections(server), do:
    GenServer.call({:global, server}, :inspections)

  def inspect_item(server), do:
    GenServer.call({:global, server}, :inspect_item, 200_000)

  def throw_to(server, item), do:
    GenServer.call({:global, server}, {:add_item_to_end, item})

  # SERVER
  @impl true
  def init(monkey) do
    {:ok, monkey}
  end

  @impl true
  def handle_call(:state, _from, state) do
    {:reply, state, state}
  end

  @impl true
  def handle_call(:items, _from, state) do
    items = Map.get(state, :items)
    {:reply, items, state}
  end

  @impl true
  def handle_call(:inspections, _from, state) do
    inspections = Map.get(state, :inspections)
    {:reply, inspections, state}
  end

  @impl true
  def handle_call(:inspect_item, _from, state) do
    %{
      monkey: monkey,
      items: items,
      operation: operation,
      test_divisibility: test_divisibility,
      throw_if_true: throw_if_true,
      throw_if_false: throw_if_false,
      inspections: inspections
    } = state
    [first | remainder] = items

    new_worry = first |> operation.() |> rem(@monkey_factor) # |> Kernel.div(3) # part 1

    IO.inspect new_worry

    if rem(new_worry, test_divisibility) == 0 do
      throw_to(throw_if_true, new_worry)
    else
      throw_to(throw_if_false, new_worry)
    end

    {
      :reply,
      "inspected",
      %{ state |
        items: remainder,
        inspections: inspections + 1
      }
    }
  end

  @impl true
  def handle_call({:add_item_to_end, item}, _from, state) do
    items = Map.get(state, :items)

    {
      :reply,
      "item thrown",
      %{ state |
        items: items ++ [item]
      }
    }
  end
end

Most Liked

adamu

adamu

It’s just occurred to me that the monkies are prime, making them… prime apes.

jkwchui

jkwchui

A bit off-topic, but for Day 12, Paul Schoenfelder’s libgraph make it easy to generate a directed graph / do path-finding.

Day 12 spoiler

The edges does not need to be weighted, but they do need to be directed. I misread the prompt and took a looong time to figure out what happened. You are forbidden to climb more than one level, but it is permissible to jump off a cliff.

stevensonmt

stevensonmt

Yeah, adding that LCM step made part 2 work for me. I think this is an issue where being told the result was overflowing the integer type instead of silently moving to a BigNum (or whaterver Erlang does under the hood) would have clued me in to what the problem was a lot sooner.
I tried changing lists to Erlang arrays to make it faster. I tried using Erlang counters to make it faster after watching @ityonemo’s Advent of Elixir youtube video on counters. I tried making each round use concurrent threads for each item to reduce the time each round would take. None of that helped. It was all this simple math trick to keep from overflowing the integer type.

code-shoily

code-shoily

When one codes both Erlang and Elixir on the same night.

Screenshot 2022-12-14 at 12.13.45 PM

LostKobrakai

LostKobrakai

Yeah, I tried to brute force it and it took few seconds to get to round 600, then minutes to get to round 800 and I don’t think I ever saw it go beyond round 900 before I gave up (having had breakfast in between). Using only the remainder make the 10k complete in seconds. I would’ve never figured that out without looking at others’ solutions though. It still kinda blows my mind that applying operations on the remained instead of the whole number somehow yield the same results (given multiplication and additions all the same).

Where Next?

Popular in Challenges Top

sb8244
Note: This topic is to talk about Day 10 of the Advent of Code 2019 . There is a private leaderboard for elixirforum members. You can jo...
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
QuinnWilton
Note: This topic is to talk about Day 7 of the Advent of Code 2019 . There is a private leaderboard for elixirforum members. You can joi...
New
adamu
I said I was on a break, but I took a sneak peak and it looked fun so… Part 1 completes in half a millisecond with a single pass of the ...
New
Aetherus
Today’s challenge is quite interesting. I ended up using Zipper to solve this problem. Maybe I overengineered quite a bit. The data stru...
New
bjorng
This topic is about Day 14 of the Advent of Code 2020 . Thanks to @egze, we have a private leaderboard: https://adventofcode.com/2020/l...
New
bjorng
Note: This topic is to talk about Day 23 of the Advent of Code. For general discussion about the Advent of Code 2018 and links to topics...
New
bjorng
This topic is about Day 15 of the Advent of Code 2021. We have a private leaderboard (shared with users of Erlang Forums): https://adve...
New
seeplusplus
Hello all, hopefully I post this before someone else does and I don’t dupe. IMO Day 4 was much easier than Day 3 (yay, I can sleep befor...
New
coen.bakker
Since I started using Elixir, I have benefited greatly from being able to study various open-source projects. The codebase of LiveBook, i...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement