Skip to main content

aoc/year2019/
day14.rs

1//! # Space Stoichiometry
2//!
3//! Sorting the reactions in [topological order](https://en.wikipedia.org/wiki/Topological_sorting)
4//! from `FUEL` at the start to `ORE` at the end, allows us to process each reaction only once.
5use crate::util::hash::*;
6use crate::util::iter::*;
7use crate::util::parse::*;
8
9struct Ingredient {
10    amount: u64,
11    chemical: usize,
12}
13
14pub struct Reaction {
15    amount: u64,
16    chemical: usize,
17    ingredients: Vec<Ingredient>,
18}
19
20/// To speed things up when processing, we use a temporary map to convert chemical names into
21/// contiguous indices.
22pub fn parse(input: &str) -> Vec<Reaction> {
23    let lines: Vec<_> = input.lines().collect();
24
25    // Reactions are indexed by output chemical. ORE has no reaction so keeps the default.
26    let mut reactions = Vec::from_fn(lines.len() + 1, |chemical| Reaction {
27        amount: 0,
28        chemical,
29        ingredients: Vec::new(),
30    });
31
32    // Assign FUEL and ORE known indices as we'll need to look them up later.
33    let mut indices = FastMap::build([("FUEL", 0), ("ORE", 1)]);
34
35    let mut lookup = |s| {
36        let size = indices.len();
37        *indices.entry(s).or_insert(size)
38    };
39
40    for line in lines {
41        let mut tokens = line
42            .rsplit(|c: char| !c.is_ascii_alphanumeric())
43            .filter(|s| !s.is_empty())
44            .chunk::<2>();
45
46        // Assigns other indices in the arbitrary order that chemicals are encountered.
47        let [kind, amount] = tokens.next().unwrap();
48        let chemical = lookup(kind);
49
50        let reaction = &mut reactions[chemical];
51        reaction.amount = amount.unsigned();
52
53        for [kind, amount] in tokens {
54            let chemical = lookup(kind);
55            reaction.ingredients.push(Ingredient { amount: amount.unsigned(), chemical });
56        }
57    }
58
59    // Sort reactions in topological order.
60    let mut order = vec![0; reactions.len()];
61    topological(&reactions, &mut order, 0, 0);
62    reactions.sort_unstable_by_key(|r| order[r.chemical]);
63    reactions
64}
65
66/// Calculate the amount of ore needed for 1 fuel. This will be the most ore needed per unit of
67/// fuel. Larger amounts of fuel can use some of the leftover chemicals from intermediate reactions.
68pub fn part1(input: &[Reaction]) -> u64 {
69    ore(input, 1)
70}
71
72/// Find the maximum amount of fuel possible from 1 trillion ore with an efficient binary search.
73pub fn part2(input: &[Reaction]) -> u64 {
74    let threshold = 1_000_000_000_000;
75    let mut start = 1_u64;
76    let mut end = threshold;
77
78    while start != end {
79        let middle = (start + end).div_ceil(2);
80
81        if ore(input, middle) > threshold {
82            end = middle - 1;
83        } else {
84            start = middle;
85        }
86    }
87
88    start
89}
90
91/// Sort reactions in topological order from FUEL at the root to ORE at the leaves. Reactions may
92/// occur more than once at different depths in the graph, so we take the maximum depth.
93fn topological(reactions: &[Reaction], order: &mut [usize], chemical: usize, depth: usize) {
94    order[chemical] = order[chemical].max(depth);
95
96    for ingredient in &reactions[chemical].ingredients {
97        topological(reactions, order, ingredient.chemical, depth + 1);
98    }
99}
100
101/// Run the reactions to find ore needed. Each chemical is processed only once, so we don't need
102/// to track excess values of intermediate chemicals.
103fn ore(reactions: &[Reaction], amount: u64) -> u64 {
104    let mut total = vec![0; reactions.len()];
105    total[0] = amount;
106
107    for reaction in &reactions[..reactions.len() - 1] {
108        let multiplier = total[reaction.chemical].div_ceil(reaction.amount);
109
110        for ingredient in &reaction.ingredients {
111            total[ingredient.chemical] += multiplier * ingredient.amount;
112        }
113    }
114
115    total[1]
116}