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

Advent of Code 2023 - Day 19 (incomplete)

2023/elixir/livebooks/day19.livemd

Advent of Code 2023 - Day 19 (incomplete)

Mix.install([
  {:kino_aoc, "~> 0.1"}
])

Introduction

— Day 19: Aplenty —

The Elves of Gear Island are thankful for your help and send you on your way. They even have a hang glider that someone stole from Desert Island; since you’re already going that direction, it would help them a lot if you would use it to get down there and return it to them.

As you reach the bottom of the relentless avalanche of machine parts, you discover that they’re already forming a formidable heap. Don’t worry, though - a group of Elves is already here organizing the parts, and they have a system.

To start, each part is rated in each of four categories:

  • x: Extremely cool looking
  • m: Musical (it makes a noise when you hit it)
  • a: Aerodynamic
  • s: Shiny

Then, each part is sent through a series of workflows that will ultimately accept or reject the part. Each workflow has a name and contains a list of rules; each rule specifies a condition and where to send the part if the condition is true. The first rule that matches the part being considered is applied immediately, and the part moves on to the destination described by the rule. (The last rule in each workflow has no condition and always applies if reached.)

Consider the workflow ex{x>10:one,m<20:two,a>30:R,A}. This workflow is named ex and contains four rules. If workflow ex were considering a specific part, it would perform the following steps in order:

  • Rule “x>10:one“: If the part’s x is more than 10, send the part to the workflow named one.
  • Rule “m<20:two“: Otherwise, if the part’s m is less than 20, send the part to the workflow named two.
  • Rule “a>30:R“: Otherwise, if the part’s a is more than 30, the part is immediately rejected (R).
  • Rule “A“: Otherwise, because no other rules matched the part, the part is immediately accepted (A).

If a part is sent to another workflow, it immediately switches to the start of that workflow instead and never returns. If a part is accepted (sent to A) or rejected (sent to R), the part immediately stops any further processing.

The system works, but it’s not keeping up with the torrent of weird metal shapes. The Elves ask if you can help sort a few parts and give you the list of workflows and some part ratings (your puzzle input). For example:

px{a<2006:qkq,m>2090:A,rfg}
pv{a>1716:R,A}
lnx{m>1548:A,A}
rfg{s<537:gd,x>2440:R,A}
qs{s>3448:A,lnx}
qkq{x<1416:A,crn}
crn{x>2662:A,R}
in{s<1351:px,qqz}
qqz{s>2770:qs,m<1801:hdj,R}
gd{a>3333:R,R}
hdj{m>838:A,pv}

{x=787,m=2655,a=1222,s=2876}
{x=1679,m=44,a=2067,s=496}
{x=2036,m=264,a=79,s=2244}
{x=2461,m=1339,a=466,s=291}
{x=2127,m=1623,a=2188,s=1013}

The workflows are listed first, followed by a blank line, then the ratings of the parts the Elves would like you to sort. All parts begin in the workflow named in. In this example, the five listed parts go through the following workflows:

  • {x=787,m=2655,a=1222,s=2876}: in -> qqz -> qs -> lnx -> A
  • {x=1679,m=44,a=2067,s=496}: in -> px -> rfg -> gd -> R
  • {x=2036,m=264,a=79,s=2244}: in -> qqz -> hdj -> pv -> A
  • {x=2461,m=1339,a=466,s=291}: in -> px -> qkq -> crn -> R
  • {x=2127,m=1623,a=2188,s=1013}: in -> px -> rfg -> A

Ultimately, three parts are accepted. Adding up the x, m, a, and s rating for each of the accepted parts gives 7540 for the part with x=787, 4623 for the part with x=2036, and 6951 for the part with x=2127. Adding all of the ratings for all of the accepted parts gives the sum total of 19114.

Sort through all of the parts you’ve been given; what do you get if you add together all of the rating numbers for all of the parts that ultimately get accepted?

— Part Two —

Even with your help, the sorting process still isn’t fast enough.

One of the Elves comes up with a new plan: rather than sort parts individually through all of these workflows, maybe you can figure out in advance which combinations of ratings will be accepted or rejected.

Each of the four ratings (x, m, a, s) can have an integer value ranging from a minimum of 1 to a maximum of 4000. Of all possible distinct combinations of ratings, your job is to figure out which ones will be accepted.

In the above example, there are 167409079868000 distinct combinations of ratings that will be accepted.

Consider only your list of workflows; the list of part ratings that the Elves wanted you to sort is no longer relevant. How many distinct combinations of ratings will be accepted by the Elves’ workflows?

Puzzle

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "19", System.fetch_env!("LB_AOC_SESSION"))
IO.puts(puzzle_input)

Parser

Code - Parser

defmodule Parser do
  def parse(input) do
    input
    |> String.split("\n\n", trim: true)
    |> then(fn [workflows, ratings] ->
      workflows =
        workflows
        |> String.split("\n", trim: true)
        |> Enum.reduce(%{}, fn line, acc ->
          [part, flow] =
            line
            |> String.split(["{", "}"], trim: true)

          flow =
            flow
            |> String.split(",", trim: true)
            |> Enum.map(fn params ->
              params = Regex.scan(~r/^[xmas]|[<>]|\d+|[a-zA-Z]+/, params) |> List.flatten()

              case params do
                [cat, sig, val, dest] ->
                  {cat, sig, String.to_integer(val), dest}

                dest ->
                  dest |> Enum.join()
              end
            end)

          Map.put_new(acc, part, flow)
        end)

      ratings =
        ratings
        |> String.split("\n", trim: true)
        |> Enum.map(fn line ->
          line
          |> String.split(["{", ",", "}"], trim: true)
          |> Enum.reduce(%{}, fn rating, acc ->
            [category, value] = rating |> String.split("=", trim: true)
            Map.put_new(acc, category, String.to_integer(value))
          end)
        end)

      {workflows, ratings}
    end)
  end
end

Tests - Parser

ExUnit.start(autorun: false)

defmodule ParserTest do
  use ExUnit.Case, async: true
  import Parser

  @input """
  px{a<2006:qkq,m>2090:A,rfg}
  pv{a>1716:R,A}
  lnx{m>1548:A,A}
  rfg{s<537:gd,x>2440:R,A}
  qs{s>3448:A,lnx}
  qkq{x<1416:A,crn}
  crn{x>2662:A,R}
  in{s<1351:px,qqz}
  qqz{s>2770:qs,m<1801:hdj,R}
  gd{a>3333:R,R}
  hdj{m>838:A,pv}

  {x=787,m=2655,a=1222,s=2876}
  {x=1679,m=44,a=2067,s=496}
  {x=2036,m=264,a=79,s=2244}
  {x=2461,m=1339,a=466,s=291}
  {x=2127,m=1623,a=2188,s=1013}
  """
  @expected {
    %{
      "px" => [{"a", "<", 2006, "qkq"}, {"m", ">", 2090, "A"}, "rfg"],
      "pv" => [{"a", ">", 1716, "R"}, "A"],
      "lnx" => [{"m", ">", 1548, "A"}, "A"],
      "rfg" => [{"s", "<", 537, "gd"}, {"x", ">", 2440, "R"}, "A"],
      "qs" => [{"s", ">", 3448, "A"}, "lnx"],
      "qkq" => [{"x", "<", 1416, "A"}, "crn"],
      "crn" => [{"x", ">", 2662, "A"}, "R"],
      "in" => [{"s", "<", 1351, "px"}, "qqz"],
      "qqz" => [{"s", ">", 2770, "qs"}, {"m", "<", 1801, "hdj"}, "R"],
      "gd" => [{"a", ">", 3333, "R"}, "R"],
      "hdj" => [{"m", ">", 838, "A"}, "pv"]
    },
    [
      %{"x" => 787, "m" => 2655, "a" => 1222, "s" => 2876},
      %{"x" => 1679, "m" => 44, "a" => 2067, "s" => 496},
      %{"x" => 2036, "m" => 264, "a" => 79, "s" => 2244},
      %{"x" => 2461, "m" => 1339, "a" => 466, "s" => 291},
      %{"x" => 2127, "m" => 1623, "a" => 2188, "s" => 1013}
    ]
  }

  test "parse test" do
    assert parse(@input) == @expected
  end
end

ExUnit.run()

Part One

Code - Part 1

defmodule PartOne do
  def solve(input) do
    IO.puts("--- Part One ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    {workflows, ratings} =
      input
      |> Parser.parse()

    ratings
    |> Enum.map(fn rating ->
      case process_parts(workflows, rating, 0, "in") do
        "A" -> sum_rating(rating)
        _ -> 0
      end
    end)
    |> Enum.sum()
  end

  def process_parts(_, _, _, part) when part == "A" or part == "R", do: part

  def process_parts(workflows, rating, index, part) do
    params =
      workflows
      |> Map.get(part)
      |> Enum.at(index)

    case params do
      {cat, sig, val, dest} ->
        true? =
          case sig do
            ">" -> Map.get(rating, cat) > val
            _ -> Map.get(rating, cat) < val
          end

        case true? do
          true -> process_parts(workflows, rating, 0, dest)
          false -> process_parts(workflows, rating, index + 1, part)
        end

      dest ->
        process_parts(workflows, rating, 0, dest)
    end
  end

  def sum_rating(%{"x" => x, "m" => m, "a" => a, "s" => s}) do
    x + m + a + s
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

defmodule PartOneTest do
  use ExUnit.Case, async: true
  import PartOne

  @input """
  px{a<2006:qkq,m>2090:A,rfg}
  pv{a>1716:R,A}
  lnx{m>1548:A,A}
  rfg{s<537:gd,x>2440:R,A}
  qs{s>3448:A,lnx}
  qkq{x<1416:A,crn}
  crn{x>2662:A,R}
  in{s<1351:px,qqz}
  qqz{s>2770:qs,m<1801:hdj,R}
  gd{a>3333:R,R}
  hdj{m>838:A,pv}

  {x=787,m=2655,a=1222,s=2876}
  {x=1679,m=44,a=2067,s=496}
  {x=2036,m=264,a=79,s=2244}
  {x=2461,m=1339,a=466,s=291}
  {x=2127,m=1623,a=2188,s=1013}
  """
  @expected 19114

  test "part one" do
    assert run(@input) == @expected
  end
end

ExUnit.run()

Solution - Part 1

PartOne.solve(puzzle_input)

Part Two

Code - Part 2

defmodule PartTwo do
  def solve(input) do
    IO.puts("--- Part Two ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
  end

  def factorial(0), do: 1

  def factorial(n) when n > 0 do
    Enum.reduce(1..n, &amp;*/2)
  end

  def combinatoric(n, r) do
    div(factorial(n), factorial(r) * factorial(n - r))
  end

  def permutation(n, array) do
    num = factorial(n)

    den =
      array
      |> Enum.map(&amp;factorial(&amp;1))
      |> Enum.product()

    num / den
  end

  def permutations([]), do: [[]]

  def permutations(list) do
    for elem <- list,
        rest <- permutations(list -- [elem]),
        into: MapSet.new(),
        do: [elem | rest]
  end
end
PartTwo.permutation(4, [8])

Tests - Part 2

ExUnit.start(autorun: false)

defmodule PartTwoTest do
  use ExUnit.Case, async: true
  import PartTwo

  @input ""
  @expected nil

  test "part two" do
    assert run(@input) == @expected
  end
end

ExUnit.run()

Solution - Part 2

PartTwo.solve(puzzle_input)