Skip to main content

aoc/year2019/
day06.rs

1//! # Universal Orbit Map
2//!
3//! Each object name is 3 characters long, using the characters `A` to `Z` and `0` to `9`.
4//! This is only 36³ = 46656 possibilities, so we can use
5//! [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function) to store contiguous
6//! indices for each object, allowing us to lookup a perfect *minimal* hash for each object.
7//!
8//! This is twice as fast as using a [`FastMap`] to lookup the indices.
9//!
10//! [`FastMap`]: crate::util::hash
11
12/// Convert 3 character object names to contiguous indices for faster lookup.
13pub fn parse(input: &str) -> Vec<usize> {
14    // Hash each 3 character object name as a base 36 number.
15    let perfect_hash = |object| usize::from_str_radix(object, 36).unwrap();
16
17    // Pre-seed known indices for objects that we need to specifically lookup later.
18    let mut indices = vec![0_u16; 36 * 36 * 36];
19    indices[perfect_hash("COM")] = 1;
20    indices[perfect_hash("SAN")] = 2;
21    indices[perfect_hash("YOU")] = 3;
22    let mut current = 4;
23
24    // Assign sequential indices to each object the first time that we encounter it.
25    // 0 is used as a special "empty" value.
26    let mut lookup = |s| {
27        let hash = perfect_hash(s);
28        if indices[hash] == 0 {
29            indices[hash] = current;
30            current += 1;
31        }
32        usize::from(indices[hash])
33    };
34
35    // Build parent-child relationships for each object. Add one extra for the unused 0 special
36    // value and another as there is always one more object than input lines.
37    let lines: Vec<_> = input.lines().collect();
38    let mut parent = vec![0; lines.len() + 2];
39
40    for line in lines {
41        let left = lookup(&line[0..3]);
42        let right = lookup(&line[4..7]);
43        parent[right] = left;
44    }
45
46    parent
47}
48
49/// Recursively follow parent relationships all the way to the root COM object. Cache each object's
50/// depth in order to avoid unnecessary work.
51pub fn part1(input: &[usize]) -> u64 {
52    fn orbits(parent: &[usize], cache: &mut [Option<u64>], index: usize) -> u64 {
53        cache[index].unwrap_or_else(|| {
54            let result = 1 + orbits(parent, cache, parent[index]);
55            cache[index] = Some(result);
56            result
57        })
58    }
59
60    let cache = &mut vec![None; input.len()];
61    cache[0] = Some(0); // Special empty value
62    cache[1] = Some(0); // COM
63    (0..input.len()).map(|index| orbits(input, cache, index)).sum()
64}
65
66/// Trace Santa's path all the way to the root COM object keeping track of distance. Then
67/// trace our path to the root. As soon as we encounter a non-zero distance then we've hit
68/// the first common ancestor and can calculate the required transfers.
69pub fn part2(input: &[usize]) -> u16 {
70    let mut distance = vec![0; input.len()];
71    let mut index = 2; // SAN
72    let mut count = 0;
73
74    // COM = 1
75    while index != 1 {
76        distance[index] = count;
77        index = input[index];
78        count += 1;
79    }
80
81    index = 3; // YOU
82    count = 0;
83
84    while distance[index] == 0 {
85        index = input[index];
86        count += 1;
87    }
88
89    distance[index] + count - 2
90}