aoc/year2018/
day07.rs

1//! # The Sum of Its Parts
2//!
3//! Part one is a [topological sort](https://en.wikipedia.org/wiki/Topological_sorting)
4//! of the steps based on the dependencies between them.
5use crate::util::hash::*;
6use std::collections::BTreeMap;
7
8type Input = FastMap<u8, Step>;
9
10#[derive(Clone, Default)]
11pub struct Step {
12    remaining: u32,
13    children: Vec<u8>,
14}
15
16pub fn parse(input: &str) -> Input {
17    let mut steps: Input = FastMap::new();
18
19    for line in input.lines().map(str::as_bytes) {
20        // Each step is a single uppercase letter.
21        let from = line[5];
22        let to = line[36];
23
24        // Add all steps that depend on this one to children vec.
25        steps.entry(from).or_default().children.push(to);
26
27        // Count how many steps must finish before this step is ready.
28        // We only need the total count, the exact steps are not necessary.
29        steps.entry(to).or_default().remaining += 1;
30    }
31
32    steps
33}
34
35pub fn part1(input: &Input) -> String {
36    // Move all steps with no dependencies to the `ready` map. A `BTreeMap` is sorted by key
37    // so will retrieve steps in alphabetical order.
38    let (mut ready, mut blocked) = split_by_readiness(input);
39    let mut done = String::new();
40
41    while let Some((key, step)) = ready.pop_first() {
42        // Keep track of the order of completed tasks.
43        done.push(key as char);
44
45        // For each dependent step, decrease the remaining count by one. Once a step reaches zero
46        // then all its dependencies have been completed and we can move it to the `ready` map.
47        for key in step.children {
48            let mut step = blocked.remove(&key).unwrap();
49            step.remaining -= 1;
50
51            if step.remaining == 0 {
52                ready.insert(key, step);
53            } else {
54                blocked.insert(key, step);
55            }
56        }
57    }
58
59    done
60}
61
62pub fn part2(input: &Input) -> u32 {
63    part2_testable(input, 5, 60)
64}
65
66pub fn part2_testable(input: &Input, max_workers: usize, base_duration: u32) -> u32 {
67    // Same as part one, move all tasks that are root nodes to the `ready` map.
68    let (mut ready, mut blocked) = split_by_readiness(input);
69
70    // Loop until there are no more steps available and all workers are idle.
71    let mut time = 0;
72    let mut workers = Vec::new();
73
74    while !ready.is_empty() || !workers.is_empty() {
75        // Assign any steps to available workers until one or the other runs out first.
76        while !ready.is_empty() && workers.len() < max_workers {
77            let (key, step) = ready.pop_first().unwrap();
78            let finish = time + base_duration + (key - 64) as u32;
79
80            // Sort workers in reverse order, so that the worker that will finish first is at
81            // the end of the vec.
82            workers.push((finish, step));
83            workers.sort_unstable_by_key(|(time, _)| u32::MAX - time);
84        }
85
86        // Fast forward time until the earliest available worker finishes their step.
87        // This may not unblock a dependent step right away in which case the outer loop will
88        // bring things back here for another worker to complete.
89        let (finish, step) = workers.pop().unwrap();
90        time = finish;
91
92        // Update dependent tasks the same as part one.
93        for key in step.children {
94            let mut step = blocked.remove(&key).unwrap();
95            step.remaining -= 1;
96
97            if step.remaining == 0 {
98                ready.insert(key, step);
99            } else {
100                blocked.insert(key, step);
101            }
102        }
103    }
104
105    time
106}
107
108fn split_by_readiness(input: &Input) -> (BTreeMap<u8, Step>, FastMap<u8, Step>) {
109    let mut ready = BTreeMap::new();
110    let mut blocked = FastMap::new();
111
112    for (key, step) in input.clone() {
113        if step.remaining == 0 {
114            ready.insert(key, step);
115        } else {
116            blocked.insert(key, step);
117        }
118    }
119
120    (ready, blocked)
121}