Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Advent of Code 2024/11

2024/11.livemd

Advent of Code 2024/11

Mix.install([
  {:kino, "~> 0.14.2"}
])

Section

input = Kino.Input.textarea("input")
defmodule AoC2024_11 do
  def parse(input) do
    Kino.Input.read(input)
    |> String.split("\s", trim: true)
  end

  def update_collection(collection, number, counter) do
    Map.merge(collection, %{ number => (collection[number] || 0) + counter })
  end
  def update_collection(collection, new_number, counter, another_new_number) do
    collection = update_collection(collection, new_number, counter)
    Map.merge(collection, %{another_new_number => (collection[another_new_number] || 0) + counter})
  end

  def blink(collection, "0", counter), do: update_collection(collection, "1", counter)
  def blink(collection, number, counter) when rem(div(bit_size(number),8),2) == 0 do
    split = String.split_at(number, div(String.length(number),2)) 
    update_collection(collection, Integer.to_string(String.to_integer(elem(split,0))), counter, Integer.to_string(String.to_integer(elem(split,1))))
  end 
  def blink(collection, number, counter), do: update_collection(collection, Integer.to_string(String.to_integer(number) * 2024), counter) 
  
  def part_1(input) do
    parsed = input
    |> parse
    
    0..24
    |> Range.to_list
    |> Enum.reduce(
      Enum.reduce(parsed, %{}, fn el, acc -> Map.merge(acc, %{el => 1}) end),
      fn i, collection ->
        res = Enum.reduce(Map.keys(collection), %{}, fn el, acc -> 
          IO.inspect({acc, el, blink(acc, el, collection[el])})
          blink(acc, el, collection[el]) 
        end)
        IO.inspect({i, res})
        res
      end)
    |> Map.to_list
    |> Enum.map(fn {_, count} -> count end)
    |> dbg()
    |> Enum.sum
  end

  def part_2(input) do
parsed = input
    |> parse
    
    0..74
    |> Range.to_list
    |> Enum.reduce(
      Enum.reduce(parsed, %{}, fn el, acc -> Map.merge(acc, %{el => 1}) end),
      fn i, collection ->
        res = Enum.reduce(Map.keys(collection), %{}, fn el, acc -> 
          IO.inspect({acc, el, blink(acc, el, collection[el])})
          blink(acc, el, collection[el]) 
        end)
        IO.inspect({i, res})
        res
      end)
    |> Map.to_list
    |> Enum.map(fn {_, count} -> count end)
    |> dbg()
    |> Enum.sum
  end
end
AoC2024_11.part_1(input)
AoC2024_11.part_2(input)