From 31bcb54699d35a8caf6c3fb2887eebc904282537 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20LUDWIG?= Date: Tue, 13 Feb 2024 00:52:59 +0100 Subject: [PATCH] feat: day 8 part 2, solution brute force (slow) --- day_8/input_example_3.txt | 10 ++++++++++ day_8/src/lib.rs | 34 ++++++++++++++++++++++++++++++++++ day_8/src/main.rs | 4 ++-- 3 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 day_8/input_example_3.txt diff --git a/day_8/input_example_3.txt b/day_8/input_example_3.txt new file mode 100644 index 0000000..5b3fa58 --- /dev/null +++ b/day_8/input_example_3.txt @@ -0,0 +1,10 @@ +LR + +11A = (11B, XXX) +11B = (XXX, 11Z) +11Z = (11B, XXX) +22A = (22B, XXX) +22B = (22C, 22C) +22C = (22Z, 22Z) +22Z = (22B, 22B) +XXX = (XXX, XXX) diff --git a/day_8/src/lib.rs b/day_8/src/lib.rs index 584f458..97d5a14 100644 --- a/day_8/src/lib.rs +++ b/day_8/src/lib.rs @@ -113,6 +113,35 @@ pub fn part_1(input: &str) -> usize { steps } +pub fn part_2(input: &str) -> usize { + let desert_map = DesertMap::from_str(input).unwrap_or_default(); + let mut current_step_keys: Vec = desert_map + .nodes + .keys() + .filter(|key| key.ends_with('A')) + .map(|key| key.to_string()) + .collect(); + let mut steps = 0; + while !current_step_keys + .iter() + .all(|step_key| step_key.ends_with('Z')) + { + let direction_index = steps % desert_map.directions.len(); + let current_direction = &desert_map.directions[direction_index]; + for current_step_key in current_step_keys.iter_mut() { + let current_step_value = + if let Some(step_value) = desert_map.nodes.get(current_step_key) { + step_value + } else { + break; + }; + *current_step_key = current_step_value[current_direction.index()].to_string(); + } + steps += 1; + } + steps +} + #[cfg(test)] mod day_8_tests { use super::*; @@ -131,4 +160,9 @@ mod day_8_tests { fn test_part_1() { assert_eq!(part_1(include_str!("../input.txt")), 15871); } + + #[test] + fn test_part_2_example_3() { + assert_eq!(part_2(include_str!("../input_example_3.txt")), 6); + } } diff --git a/day_8/src/main.rs b/day_8/src/main.rs index 453d25f..b891e6b 100644 --- a/day_8/src/main.rs +++ b/day_8/src/main.rs @@ -1,8 +1,8 @@ -use day_8::part_1; +use day_8::{part_1, part_2}; fn main() { let input = include_str!("../input.txt"); println!("- Day 8: Haunted Wasteland -"); println!("Answer Part 1: {}", part_1(input)); - // println!("Answer Part 2: {}", part_2(input)); + println!("Answer Part 2: {}", part_2(input)); }