Skip to main content

aoc/year2024/
day21.rs

1//! # Keypad Conundrum
2//!
3//! Each key sequence always ends in `A`. This means that we can consider each group of button
4//! presses between `A`s independently using a recursive approach with memoization to efficiently
5//! compute the minimum presses needed for any depth of chained robots.
6use std::iter::{once, repeat_n};
7
8use crate::util::hash::*;
9use crate::util::parse::*;
10use crate::util::point::*;
11
12type Input = (Vec<(String, usize)>, Combinations);
13type Combinations = FastMap<(char, char), Vec<String>>;
14type Cache = FastMap<(char, char, usize), usize>;
15
16/// Convert codes to pairs of the sequence itself with the numeric part.
17/// The pad combinations are the same between both parts so only need to be computed once.
18pub fn parse(input: &str) -> Input {
19    let pairs = input.lines().map(String::from).zip(input.iter_unsigned()).collect();
20    (pairs, pad_combinations())
21}
22
23pub fn part1(input: &Input) -> usize {
24    chain(input, 3)
25}
26
27pub fn part2(input: &Input) -> usize {
28    chain(input, 26)
29}
30
31fn chain(input: &Input, depth: usize) -> usize {
32    let (pairs, combinations) = input;
33    let cache = &mut FastMap::with_capacity(500);
34    pairs.iter().map(|(code, numeric)| dfs(cache, combinations, code, depth) * numeric).sum()
35}
36
37fn dfs(cache: &mut Cache, combinations: &Combinations, code: &str, depth: usize) -> usize {
38    // Number of presses for the last keypad is just the length of the sequence.
39    if depth == 0 {
40        return code.len();
41    }
42
43    // All keypads start with `A`, either the initial position of the keypad or the trailing `A`
44    // from the previous sequence at this level.
45    once('A')
46        .chain(code.chars())
47        .zip(code.chars())
48        .map(|(previous, current)| {
49            // Check each pair of characters, memoizing results.
50            let key = (previous, current, depth);
51
52            cache.get(&key).copied().unwrap_or_else(|| {
53                // Each transition has either 1 or 2 possibilities.
54                // Pick the sequence that results in the minimum keypresses.
55                let presses = combinations[&(previous, current)]
56                    .iter()
57                    .map(|next| dfs(cache, combinations, next, depth - 1))
58                    .min()
59                    .unwrap();
60                cache.insert(key, presses);
61                presses
62            })
63        })
64        .sum()
65}
66
67/// Compute keypresses needed for all possible transitions for both numeric and directional
68/// keypads. There are no distinct pairs shared between the keypads so they can use the same map
69/// without conflict.
70fn pad_combinations() -> Combinations {
71    let numeric_gap = Point::new(0, 3);
72    let numeric_keys = [
73        ('7', Point::new(0, 0)),
74        ('8', Point::new(1, 0)),
75        ('9', Point::new(2, 0)),
76        ('4', Point::new(0, 1)),
77        ('5', Point::new(1, 1)),
78        ('6', Point::new(2, 1)),
79        ('1', Point::new(0, 2)),
80        ('2', Point::new(1, 2)),
81        ('3', Point::new(2, 2)),
82        ('0', Point::new(1, 3)),
83        ('A', Point::new(2, 3)),
84    ];
85
86    let directional_gap = Point::new(0, 0);
87    let directional_keys = [
88        ('^', Point::new(1, 0)),
89        ('A', Point::new(2, 0)),
90        ('<', Point::new(0, 1)),
91        ('v', Point::new(1, 1)),
92        ('>', Point::new(2, 1)),
93    ];
94
95    let mut combinations = FastMap::with_capacity(145);
96    pad_routes(&mut combinations, &numeric_keys, numeric_gap);
97    pad_routes(&mut combinations, &directional_keys, directional_gap);
98    combinations
99}
100
101/// Each route between two keys has 2 possibilities, horizontal first or vertical first.
102/// We skip any route that would cross the gap and also avoid adding the same route twice
103/// when a key is in a straight line (e.g. directly above/below or left/right). For example:
104///
105/// * `7 => A` is only `>>vvv`.
106/// * `1 => 5` is `^>` and `>^`.
107///
108/// We don't consider routes that change direction more than once as these are always longer,
109/// for example `5 => A` ignores the path `v>v`.
110fn pad_routes(combinations: &mut Combinations, pad: &[(char, Point)], gap: Point) {
111    for &(first, from) in pad {
112        for &(second, to) in pad {
113            let horizontal = || move_sequence(from.x, to.x, '>', '<');
114            let vertical = || move_sequence(from.y, to.y, 'v', '^');
115            let routes = combinations.entry((first, second)).or_default();
116
117            if Point::new(from.x, to.y) != gap {
118                routes.push(vertical().chain(horizontal()).chain(once('A')).collect());
119            }
120
121            if from.x != to.x && from.y != to.y && Point::new(to.x, from.y) != gap {
122                routes.push(horizontal().chain(vertical()).chain(once('A')).collect());
123            }
124        }
125    }
126}
127
128fn move_sequence(from: i32, to: i32, positive: char, negative: char) -> impl Iterator<Item = char> {
129    let element = if from < to { positive } else { negative };
130    let count = from.abs_diff(to) as usize;
131    repeat_n(element, count)
132}