Day 19 - Aplenty
Mix.install([:kino])
default = "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}"
Problem
https://adventofcode.com/2023/day/19
PART 1
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
: E_x_tremely cool looking -
m
: _M_usical (it makes a noise when you hit it) -
a
: _A_erodynamic -
s
: _S_hiny
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’sx
is more than10
, send the part to the workflow namedone
. -
Rule “
m<20:two
“: Otherwise, if the part’sm
is less than20
, send the part to the workflow namedtwo
. -
Rule “
a>30:R
“: Otherwise, if the part’sa
is more than30
, 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 2
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?
Solution
input = Kino.Input.textarea("Part Ratings", default: default)
values =
Kino.Input.read(input)
|> String.split("\n\n", trim: true)
|> Enum.map(&String.split(&1, "\n", trim: true))
defmodule Aplenty.Parser do
def parse_result(result) do
case result do
"A" -> :accepted
"R" -> :rejected
_ -> String.to_atom(result)
end
end
def parse_workflow(workflow) do
[name, instructions] = Regex.run(~r/([a-z]+)\{(.+)\}/, workflow, capture: :all_but_first)
instructions =
instructions
|> String.split(",")
|> Enum.map(fn instruction ->
if String.contains?(instruction, ":") do
[condition, to] = String.split(instruction, ":")
[category, value] =
condition
|> String.split(["<", ">"])
{String.to_atom(category), String.to_integer(value), String.contains?(condition, ">"),
parse_result(to)}
else
parse_result(instruction)
end
end)
|> Enum.reverse()
|> Enum.reduce(nil, fn element, acc ->
if acc == nil do
element
else
{element, acc}
end
end)
{String.to_atom(name), instructions}
end
def parse_part(part) do
part
|> String.trim_leading("{")
|> String.trim_trailing("}")
|> String.split(",", trim: true)
|> Enum.map(
&(String.split(&1, "=", trim: true)
|> then(fn [name, value] -> {String.to_atom(name), String.to_integer(value)} end))
)
end
def normalize([workflows, parts]) do
{
workflows |> Enum.map(&parse_workflow/1),
parts |> Enum.map(&parse_part/1)
}
end
end
PART 1
defmodule Aplenty.Part1 do
def get_accepted_list({workflows, parts}) do
parts
|> Enum.filter(&is_accepted(:in, &1, workflows))
end
def sum(parts) do
parts
|> Enum.flat_map(fn values ->
values |> Enum.map(&elem(&1, 1))
end)
|> Enum.sum()
end
def is_accepted(:accepted, _, _), do: true
def is_accepted(:rejected, _, _), do: false
def is_accepted(state, part, workflows) do
workflows
|> Keyword.get(state)
|> get_next_state(part)
|> is_accepted(part, workflows)
end
def get_next_state({{category, value, gt, if_state}, else_state}, part) do
part_value = Keyword.get(part, category)
fun =
if gt do
&>/2
else
&
values |> Aplenty.Parser.normalize() |> Aplenty.Part1.get_accepted_list() |> Aplenty.Part1.sum()
### PART 2
defmodule Aplenty.Part2 do def get_accepted_list(workflows) do
get_accepted_list([{:in, {1, 4000}, {1, 4000}, {1, 4000}, {1, 4000}}], workflows, [])
end
def getaccepted_list([], , acc), do: acc
def get_accepted_list([state | rest], workflows, acc) do
{states, acc} =
case get_status(state) do
:accepted ->
{rest, [state |> Tuple.to_list() |> tl() | acc]}
:rejected ->
{rest, acc}
next_state ->
{rest ++
get_other_states(Keyword.get(workflows, next_state), state |> Tuple.delete_at(0)),
acc}
end
get_accepted_list(states, workflows, acc)
end
def get_status({_state, {x_low, x_high}, {m_low, m_high}, {a_low, a_high}, {s_low, s_high}})
when x_low > x_high or m_low > m_high or a_low > a_high or s_low > s_high do
:rejected
end
def getstatus({state, , , , _}) do
state
end
def get_other_states(state, {x, m, a, s}) do
case state do
{{category, value, gt, if_state}, else_state} ->
[
[
if_state
| get_new_ranges(category, if(gt, do: :gt, else: :lt), value, x: x, m: m, a: a, s: s)
]
|> List.to_tuple()
] ++
get_other_states(
else_state,
get_new_ranges(category, if(gt, do: :lte, else: :gte), value, x: x, m: m, a: a, s: s)
|> List.to_tuple()
)
state ->
[{state, x, m, a, s}]
end
end
def get_new_ranges(category, op, value, vars) do
Keyword.update!(vars, category, fn var ->
get_new_range(var, op, value)
end)
|> Enum.map(&elem(&1, 1))
end
def get_new_range({low, high}, op, value) do
case op do
:gt -> {max(low, value + 1), high}
:lt -> {low, min(high, value - 1)}
:gte -> {max(low, value), high}
:lte -> {low, min(high, value)}
end
end
def normalize(ranges) do
ranges
|> Enum.map(fn {low, high} -> high - low + 1 end)
|> Enum.product()
end end
values |> Aplenty.Parser.normalize() |> elem(0) |> Aplenty.Part2.get_accepted_list() |> Enum.map(&Aplenty.Part2.normalize/1) |> Enum.sum()