diff --git a/2024/day21_keypad_conundrum/Cargo.toml b/2024/day21_keypad_conundrum/Cargo.toml new file mode 100644 index 0000000..df2e671 --- /dev/null +++ b/2024/day21_keypad_conundrum/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "day21_keypad_conundrum" +version = "0.1.0" +edition = "2021" + +[dependencies] + +[dev-dependencies] +# criterion = "0.5.1" + +[[bench]] +name = "test_benchmark" +harness = false diff --git a/2024/day21_keypad_conundrum/challenge.md b/2024/day21_keypad_conundrum/challenge.md new file mode 100644 index 0000000..a582838 --- /dev/null +++ b/2024/day21_keypad_conundrum/challenge.md @@ -0,0 +1,137 @@ +As you teleport onto Santa's [Reindeer-class starship](/2019/day/25), The Historians begin to panic: someone from their search party is *missing*. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by *physically typing* the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: `789`, `456`, `123`, and finally an empty gap followed by `0A`. Visually, they are arranged like this: + +``` ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ + +``` + +Unfortunately, the area outside the door is currently *depressurized* and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a *directional keypad*. + +The directional keypad has two rows of buttons: a gap / `^` (up) / `A` (activate) on the first row and `<` (left) / `v` (down) / `>` (right) on the second row. Visually, they are arranged like this: + +``` + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ + +``` + +When the robot arrives at the numeric keypad, its robotic arm is pointed at the `A` button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the `A` button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type `029A` on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +* `<` to move the arm from `A` (its initial position) to `0`. +* `A` to push the `0` button. +* `^A` to move the arm to the `2` button and push it. +* `>^^A` to move the arm to the `9` button and push it. +* `vvvA` to move the arm to the `A` button and push it. + +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type `029A`: `^^AvvvA`, `^AvvvA`, and `AvvvA`. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing *high levels of radiation* and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the `A` button in the upper right corner. After that, a *second, different* directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type `029A` on the door. One such sequence is `v<>^AAvA<^AA>A^A`. + +Unfortunately, the area containing this second directional keypad remote control is currently *`-40` degrees*! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type `029A` on the door. One such sequence is `>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A`. + +Unfortunately, the area containing this third directional keypad remote control is currently *full of Historians*, so no robots can find a clear path there. Instead, *you* will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +``` +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A + +``` + +In summary, there are the following keypads: + +* One directional keypad that *you* are using. +* Two directional keypads that *robots* are using. +* One numeric keypad (on a door) that a *robot* is using. + +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a *gap* where no button is present on the keypad, even for an instant, the robot will *panic* unrecoverably. So, don't do that. All robots will initially aim at the keypad's `A` key, wherever it is. + +To unlock the door, *five* codes will need to be typed on its numeric keypad. For example: + +``` +029A +980A +179A +456A +379A + +``` + +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +``` +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A + +``` + +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a *giant electromagnet* or *molten lava*. You'll need to make sure that for each of the five codes, you find the *shortest sequence* of button presses necessary. + +The *complexity* of a single code (like `029A`) is equal to the result of multiplying these two values: + +* The *length of the shortest sequence* of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for `029A`, this would be `68`. +* The *numeric part of the code* (ignoring leading zeroes); for `029A`, this would be `29`. + +In the above example, complexity of the five codes can be found by calculating `68 * 29`, `60 * 980`, `68 * 179`, `64 * 456`, and `64 * 379`. Adding these together produces `*126384*`. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. *What is the sum of the complexities of the five codes on your list?* + +Your puzzle answer was `123096`. + +\--- Part Two --- +---------- + +Just as the missing Historian is released, The Historians realize that a *second* member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +* One directional keypad that *you* are using. +* *25* directional keypads that *robots* are using. +* One numeric keypad (on a door) that a *robot* is using. + +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. *What is the sum of the complexities of the five codes on your list?* + +Your puzzle answer was `154517692795352`. + +Both parts of this puzzle are complete! They provide two gold stars: \*\* + +At this point, you should [return to your Advent calendar](/2024) and try another puzzle. + +If you still want to see it, you can [get your puzzle input](21/input). \ No newline at end of file diff --git a/2024/day21_keypad_conundrum/src/lib.rs b/2024/day21_keypad_conundrum/src/lib.rs new file mode 100644 index 0000000..c0fa05e --- /dev/null +++ b/2024/day21_keypad_conundrum/src/lib.rs @@ -0,0 +1,208 @@ +use core::fmt::Display; +use std::{collections::HashMap, num::ParseIntError}; + +#[derive(Debug, PartialEq, Eq)] +pub enum ParseError { + InvalidChar(char), + ParseIntError(ParseIntError) +} + +impl From for ParseError { + fn from(value: ParseIntError) -> Self { + Self::ParseIntError(value) + } +} + +impl Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidChar(e) => write!(f, "Unable to parse into a keycode: {e}"), + Self::ParseIntError(e) => write!(f, "Unable to parse keycode into numeric part: {e}"), + } + } +} + +type Coordinates = (i8, i8); + +struct KeyCode { + code: Vec, + numeric: usize, +} + +impl TryFrom<&str> for KeyCode { + type Error = ParseError; + + fn try_from(value: &str) -> Result { + let code = value.chars().map(|c| { + match c { + u if (b'7'..=b'9').contains(&(u as u8)) => Ok((u as i8 - b'7' as i8, 0)), + m if (b'4'..=b'6').contains(&(m as u8)) => Ok((m as i8 - b'4' as i8, 1)), + l if (b'1'..=b'3').contains(&(l as u8)) => Ok((l as i8 - b'1' as i8, 2)), + '0' => Ok((1, 3)), + 'A' => Ok((2, 3)), + e => Err(Self::Error::InvalidChar(e)) + } + }).collect::, _>>()?; + let numeric = value[..value.len()-1].parse()?; + Ok(Self { code, numeric, }) + } +} + +impl KeyCode { + fn buttons_to_move(arms: &mut [Arm], to: Coordinates, intermediate_robots: usize, mem: &mut HashMap<(Coordinates, Coordinates, usize), usize>) -> usize { + if let Some(res) = mem.get(&(arms[intermediate_robots].pointing, to, intermediate_robots)) { + arms[intermediate_robots].pointing = to; + return *res; + } + let res = if intermediate_robots == 0 { + arms[0].ways(to).into_iter().map(|w| w.len()).min().unwrap() + } else { + arms[intermediate_robots].ways(to).into_iter() + .map(|w| { + w.into_iter().map(|btn| { + Self::buttons_to_move(arms, btn, intermediate_robots-1, mem) + }).sum() + }).min().unwrap() + }; + mem.insert((arms[intermediate_robots].pointing, to, intermediate_robots), res); + arms[intermediate_robots].pointing = to; + res + } + + fn enter(&self, arms: &mut [Arm]) -> usize { + let mut buttons_pushed = 0; + let mut mem = HashMap::new(); + for digit in self.code.clone() { + buttons_pushed += Self::buttons_to_move(arms, digit, arms.len()-1, &mut mem); + } + buttons_pushed + } +} + +#[derive(Clone, Copy)] +struct Arm { + pointing: Coordinates, + numeric: bool, +} + +impl Arm { + fn default() -> Self { + Self { + pointing: (2, 0), + numeric: false, + } + } + + fn ways(&self, to: Coordinates) -> Vec> { + const ACTIVATE: Coordinates = (2, 0); + const UP: Coordinates = (1, 0); + const DOWN: Coordinates = (1, 1); + const LEFT: Coordinates = (0, 1); + const RIGHT: Coordinates = (2, 1); + let (dx, dy) = (to.0 - self.pointing.0, to.1 - self.pointing.1); + match (dx.signum(), dy.signum()) { + (0, 0) => vec![vec![ACTIVATE]], + (1, 0) => vec![(0..dx).map(|_| RIGHT).chain([ACTIVATE]).collect()], + (-1, 0) => vec![(0..-dx).map(|_| LEFT).chain([ACTIVATE]).collect()], + (0, 1) => vec![(0..dy).map(|_| DOWN).chain([ACTIVATE]).collect()], + (0, -1) => vec![(0..-dy).map(|_| UP).chain([ACTIVATE]).collect()], + (1, 1) => { + let mut res = vec![ + (0..dx).map(|_| RIGHT) + .chain((0..dy).map(|_| DOWN)) + .chain([ACTIVATE]).collect() + ]; + if !self.numeric || self.pointing.0 > 0 || to.1 < 3 { + res.push( + (0..dy).map(|_| DOWN) + .chain((0..dx).map(|_| RIGHT)) + .chain([ACTIVATE]).collect() + ); + } + res + }, + (-1, 1) => { + let mut res = vec![ + (0..dy).map(|_| DOWN) + .chain((0..-dx).map(|_| LEFT)) + .chain([ACTIVATE]).collect() + ]; + if self.numeric || to.0 > 0 { + res.push( + (0..-dx).map(|_| LEFT) + .chain((0..dy).map(|_| DOWN)) + .chain([ACTIVATE]).collect() + ); + } + res + }, + (1, -1) => { + let mut res = vec![ + (0..dx).map(|_| RIGHT) + .chain((0..-dy).map(|_| UP)) + .chain([ACTIVATE].into_iter()).collect() + ]; + if self.numeric || self.pointing.0 > 0 { + res.push( + (0..-dy).map(|_| UP) + .chain((0..dx).map(|_| RIGHT)) + .chain([ACTIVATE]).collect() + ); + } + res + }, + (-1, -1) => { + let mut res = vec![ + (0..-dy).map(|_| UP) + .chain((0..-dx).map(|_| LEFT)) + .chain([ACTIVATE]).collect() + ]; + if !self.numeric || to.0 > 0 || self.pointing.1 < 3 { + res.push( + (0..-dx).map(|_| LEFT) + .chain((0..-dy).map(|_| UP)) + .chain([ACTIVATE]).collect() + ); + } + res + }, + _ => unreachable!(), + } + } +} + +pub fn run(input: &str) -> Result<(usize, usize), ParseError> { + let codes: Vec<_> = input.lines().map(KeyCode::try_from).collect::, _>>()?; + let mut arms = [ + Arm::default(), + Arm::default(), + Arm { pointing: (2, 3), numeric: true, }, + ]; + let first = codes.iter().map(|c| c.enter(&mut arms) * c.numeric).sum(); + let mut arms = [Arm::default(); 26]; + arms[25] = Arm { pointing: (2, 3), numeric: true, }; + let second = codes.iter().map(|c| c.enter(&mut arms) * c.numeric).sum(); + Ok((first, second)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs::read_to_string; + + fn read_file(name: &str) -> String { + read_to_string(name).expect(&format!("Unable to read file: {name}")[..]).trim().to_string() + } + + #[test] + fn test_sample() { + let sample_input = read_file("tests/sample_input"); + assert_eq!(run(&sample_input), Ok((126384, 154115708116294))); + } + + #[test] + fn test_challenge() { + let challenge_input = read_file("tests/challenge_input"); + assert_eq!(run(&challenge_input), Ok((123096, 154517692795352))); + } +} diff --git a/2024/day21_keypad_conundrum/tests/challenge_input b/2024/day21_keypad_conundrum/tests/challenge_input new file mode 100644 index 0000000..1a64db9 --- /dev/null +++ b/2024/day21_keypad_conundrum/tests/challenge_input @@ -0,0 +1,5 @@ +279A +341A +459A +540A +085A diff --git a/2024/day21_keypad_conundrum/tests/sample_input b/2024/day21_keypad_conundrum/tests/sample_input new file mode 100644 index 0000000..4cf0c29 --- /dev/null +++ b/2024/day21_keypad_conundrum/tests/sample_input @@ -0,0 +1,5 @@ +029A +980A +179A +456A +379A