Powered by AppSignal & Oban Pro

Day 24

2024/day24.livemd

Day 24

Mix.install([:kino_aoc])

Section

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2024", "24", System.fetch_env!("LB_ADVENT_OF_CODE_SESSION"))
#puzzle_input =
  """
x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1

ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj
  """
[inputs, nodes] =
  String.split(puzzle_input, "\n\n")
inputs =
  inputs
  |> String.split("\n")
  |> Map.new(fn <<name::binary-3>> <> ": " <> val ->
    {name, String.to_integer(val)}
  end)
wires =
  nodes
  |> String.split("\n", trim: true)
  |> Map.new(fn
    <<a::binary-3, " AND ", b::binary-3, " -> ", out::binary-3>> ->
      {out, {:and, a, b}}

    <<a::binary-3, " OR ", b::binary-3, " -> ", out::binary-3>> ->
      {out, {:or, a, b}}

    <<a::binary-3, " XOR ", b::binary-3, " -> ", out::binary-3>> ->
      {out, {:xor, a, b}}
  end)
targets =
  wires
  |> Map.keys()
  |> Enum.filter(&String.starts_with?(&1, "z"))
  |> Enum.sort(:desc)
defmodule Wire do
  def eval(val, wires, inputs) do
    case Map.fetch(inputs, val) do
      {:ok, out} ->
        {out, inputs}

      :error ->
        {out, inputs} = do_compute(Map.fetch!(wires, val), wires, inputs)

        {out, Map.put(inputs, val, out)}
    end
  end

  defp do_compute({:and, a, b}, wires, inputs) do
    {a, inputs} = eval(a, wires, inputs)
    {b, inputs} = eval(b, wires, inputs)
    {Bitwise.band(a, b), inputs}
  end

  defp do_compute({:or, a, b}, wires, inputs) do
    {a, inputs} = eval(a, wires, inputs)
    {b, inputs} = eval(b, wires, inputs)
    {Bitwise.bor(a, b), inputs}
  end

  defp do_compute({:xor, a, b}, wires, inputs) do
    {a, inputs} = eval(a, wires, inputs)
    {b, inputs} = eval(b, wires, inputs)
    {Bitwise.bxor(a, b), inputs}
  end
end
{bin, _} = Enum.map_reduce(targets, inputs, &Wire.eval(&1, wires, &2))

Integer.undigits(bin, 2)