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

Day 21

2024/day21.livemd

Day 21

Mix.install([:kino_aoc])

Section

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2024", "21", System.fetch_env!("LB_ADVENT_OF_CODE_SESSION"))
{:ok, "638A\n965A\n780A\n803A\n246A"}
codes =
  puzzle_input
  |> String.split("\n", trim: true)
  |> Enum.map(fn <> <> "A" = code ->
    {String.to_charlist(code), String.to_integer(num)}
  end)
[{~c"638A", 638}, {~c"965A", 965}, {~c"780A", 780}, {~c"803A", 803}, {~c"246A", 246}]
dirpad = %{
  [?A, ?>] => ~c[vA],
  [?A, ?^] => ~c[ ~c[ ~c[v<, ?A] => ~c[^A],
  [?>, ?^] => ~c[<^A],
  [?>, ?v] => ~c[, ?<] => ~c[< ~c[>A],
  [?^, ?>] => ~c[v>A],
  [?^, ?v] => ~c[vA],
  [?^, ?<] => ~c[v ~c[>>^A],
  [?<, ?^] => ~c[>^A],
  [?<, ?v] => ~c[>A],
  [?<, ?>] => ~c[>>A],

  [?v, ?A] => ~c[>^A],
  [?v, ?^] => ~c[^A],
  [?v, ?<] => ~c[] => ~c[>A]
}
%{
  ~c"<>" => ~c">>A",
  ~c" ~c">>^A",
  ~c"<^" => ~c">^A",
  ~c" ~c">A",
  ~c"><" => ~c" ~c"^A",
  ~c">^" => ~c"<^A",
  ~c">v" => ~c" ~c"v<" => ~c"vA",
  ~c"A^" => ~c" ~c" ~c"v" => ~c"v>A",
  ~c"^A" => ~c">A",
  ~c"^v" => ~c"vA",
  ~c"v<" => ~c"" => ~c">A",
  ~c"vA" => ~c">^A",
  ~c"v^" => ~c"^A"
}
nil
defmodule Keypad do
  def naive(input, lut) do
    [?A | input]
    |> Enum.chunk_every(2, 1, :discard)
    |> Enum.flat_map(&amp;Map.get(lut, &amp;1, [?A]))
  end

  def expand(input, lut) do
    Stream.concat([?A], input)
    |> Stream.chunk_every(2, 1, :discard)
    |> Stream.flat_map(&amp;Map.get(lut, &amp;1, [?A]))
  end
end
{:module, Keypad, <<70, 79, 82, 49, 0, 0, 9, ...>>, {:expand, 2}}
nil
Keypad.expand(~c[^^AvvvA], dirpad)
|> Enum.count()

#|> Enum.map(fn {k, v} ->
#  [?A | Map.get(dirpad, k, [?A])]
#  |> Enum.chunk_every(2, 1, :discard)
#  |> Enum.map()
#end)
#|> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
#|> Map.new(fn {k, v} -> {k, Enum.sum(v)} end)
28
Keypad.naive(~c[^^AvvvA], dirpad)
|> Keypad.naive(dirpad)
|> Enum.chunk_every(2, 1, [?A])
|> Enum.frequencies()
|> Map.values()
|> Enum.sum()
68
~c">^AvAA<^A>Av<>^AvA^A^Av<^A>AAvA^Av<A>^AAAvA<^A>A"
~c">^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A" |> length
68