Skip to content

Commit

Permalink
Complete day 19
Browse files Browse the repository at this point in the history
  • Loading branch information
Riari committed Dec 20, 2023
1 parent a5eb340 commit 45b9a77
Show file tree
Hide file tree
Showing 3 changed files with 371 additions and 0 deletions.
17 changes: 17 additions & 0 deletions data/examples/19.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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}
84 changes: 84 additions & 0 deletions data/puzzles/19.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
\--- 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](9) 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'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?*

Your puzzle answer was `397134`.

\--- 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?*

Your puzzle answer was `127517902575337`.

Both parts of this puzzle are complete! They provide two gold stars: \*\*

At this point, you should [return to your Advent calendar](/2023) and try another puzzle.

If you still want to see it, you can [get your puzzle input](19/input).

You can also [Shareon [Twitter](https://twitter.com/intent/tweet?text=I%27ve+completed+%22Aplenty%22+%2D+Day+19+%2D+Advent+of+Code+2023&url=https%3A%2F%2Fadventofcode%2Ecom%2F2023%2Fday%2F19&related=ericwastl&hashtags=AdventOfCode) [Mastodon](javascript:void(0);)] this puzzle.
270 changes: 270 additions & 0 deletions src/bin/19.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
use std::{collections::HashMap, cmp::{min, max}};
use lazy_static::lazy_static;

advent_of_code::solution!(19);

lazy_static! {
static ref RE_NUMBERS: regex::Regex = regex::Regex::new(r"(\d+)").unwrap();

static ref ACCEPTED: String = "A".to_string();
static ref REJECTED: String = "R".to_string();
static ref PROCESSED: Vec<String> = vec![ACCEPTED.clone(), REJECTED.clone()];
}

#[derive(Clone, Eq, PartialEq)]
enum Result {
Accept,
Reject,
Destination,
}

impl Result {
fn from_str(s: &str) -> Result {
match s {
"A" => Result::Accept,
"R" => Result::Reject,
_ => Result::Destination,
}
}

fn to_string(&self, destination: Option<String>) -> String {
match self {
Result::Accept => ACCEPTED.clone(),
Result::Reject => REJECTED.clone(),
Result::Destination => destination.unwrap(),
}
}
}

#[derive(Clone, PartialEq)]
enum Operator {
LessThan,
GreaterThan,
}

#[derive(Clone)]
struct Rule {
category: usize, // index into part (x,m,a,s)
target_rating: u64,
operator: Operator,
}

#[derive(Clone)]
struct Step {
rule: Option<Rule>,
result: Result,
destination: Option<String>,
}

struct Workflow {
steps: Vec<Step>,
}

impl Workflow {
fn accepts(&self, ratings: &Vec<u64>) -> &Step {
for step in self.steps.iter() {
if let Some(rule) = &step.rule {
if !(match rule.operator {
Operator::LessThan => ratings[rule.category] < rule.target_rating,
Operator::GreaterThan => ratings[rule.category] > rule.target_rating,
}) {
continue;
}
}

return step;
}

unreachable!()
}
}

#[derive(Clone, Hash, PartialEq, Eq)]
struct Part {
status: String, // indicates a workflow or ACCEPTED/REJECTED
ratings: Vec<u64>,
}

fn parse(input: &str) -> (HashMap<String, Workflow>, Vec<Part>) {
let mut workflows: HashMap<String, Workflow> = HashMap::new();
let mut parts: Vec<Part> = vec![];
let mut is_parsing_workflows = true;
for line in input.lines() {
if line.is_empty() {
is_parsing_workflows = false;
continue;
}

if is_parsing_workflows {
let mut split = line.split('{');
let id = split.next().unwrap();
let steps_str = split.next().unwrap();
let mut steps: Vec<Step> = vec![];
for step_str in steps_str[..steps_str.len() - 1].split(',') {
if step_str.contains(':') {
let mut rule_split = step_str.split(':');
let target_op_rating = rule_split.next().unwrap();
let result_str = rule_split.next().unwrap();
let category = match target_op_rating.chars().nth(0).unwrap() {
'x' => 0,
'm' => 1,
'a' => 2,
's' => 3,
_ => panic!("Invalid category")
};
let operator = match target_op_rating.chars().nth(1).unwrap() {
'<' => Operator::LessThan,
'>' => Operator::GreaterThan,
_ => panic!("Invalid operator")
};
let target_rating = RE_NUMBERS.find(target_op_rating).unwrap().as_str().parse().unwrap();
let result = Result::from_str(result_str);
steps.push(Step {
rule: Some(
Rule {
category,
target_rating,
operator
}
),
destination: if result == Result::Destination { Some(result_str.to_string()) } else { None },
result
});
} else {
let result = Result::from_str(step_str);
steps.push(Step {
rule: None,
result: result.clone(),
destination: if result == Result::Destination { Some(step_str.to_string()) } else { None }
});
}
}

workflows.insert(id.to_string(), Workflow { steps });

continue;
}

let ratings: Vec<u64> = RE_NUMBERS.find_iter(line).map(|m| m.as_str().parse().unwrap()).collect();
parts.push(Part { status: "in".to_string(), ratings });
}

(workflows, parts)
}

pub fn part_one(input: &str) -> Option<u64> {
let (workflows, mut parts) = parse(input);

while parts.iter().filter(|p| !PROCESSED.contains(&p.status)).count() > 0 {
for i in (0..parts.len()).rev() {
if PROCESSED.contains(&parts[i].status) {
continue;
}

let step = workflows.get(&parts[i].status).unwrap().accepts(&parts[i].ratings);
parts[i].status = match step.result {
Result::Accept => ACCEPTED.to_string(),
Result::Reject => REJECTED.to_string(),
Result::Destination => step.destination.clone().unwrap(),
};
}
}

let mut sum = 0;
for part in parts {
if part.status == *ACCEPTED {
for rating in part.ratings {
sum += rating;
}
}
}

Some(sum)
}

// Heavily based on HyperNeutrino's solution: https://www.youtube.com/watch?v=3RwIpUegdU4
fn count_accepted_combos(ranges: &Vec<(u64, u64)>, status: String, workflows: &HashMap<String, Workflow>) -> u64 {
if status == *REJECTED {
return 0;
}

if status == *ACCEPTED {
let mut combos = 1;
for range in ranges {
combos *= range.1 - range.0 + 1;
}

return combos;
}

let workflow = workflows.get(&status).unwrap();
let mut combos = 0;
let mut ranges_clone = ranges.clone();
let mut leftover_ranges = true;
for i in 0..&workflow.steps.len() - 1 {
let step = &workflow.steps[i];
let rule = step.rule.as_ref().unwrap();

let (start, end) = ranges_clone[rule.category].clone();

let valid_range: (u64, u64);
let invalid_range: (u64, u64);
if rule.operator == Operator::LessThan {
valid_range = (start, min(rule.target_rating - 1, end));
invalid_range = (max(rule.target_rating, start), end);
} else {
valid_range = (max(rule.target_rating + 1, start), end);
invalid_range = (start, min(rule.target_rating, end));
}

if valid_range.0 <= valid_range.1 {
ranges_clone[rule.category] = valid_range;
combos += count_accepted_combos(
&ranges_clone,
step.result.to_string(step.destination.clone()),
workflows
);
}

if invalid_range.0 <= invalid_range.1 {
ranges_clone[rule.category] = invalid_range;
} else {
leftover_ranges = false;
break;
}
}

if leftover_ranges {
let fallback = &workflow.steps[&workflow.steps.len() - 1];
combos += count_accepted_combos(
&ranges_clone,
fallback.result.to_string(fallback.destination.clone()),
workflows
);
}

combos
}

pub fn part_two(input: &str) -> Option<u64> {
let (workflows, _) = parse(input);
let ranges = vec![(1 as u64, 4000 as u64); 4];
Some(count_accepted_combos(&ranges, "in".to_string(), &workflows))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(19114));
}

#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(167409079868000));
}
}

0 comments on commit 45b9a77

Please sign in to comment.