1
0

day 21 part 2

This commit is contained in:
2025-10-14 18:51:13 +02:00
parent aad74883a2
commit e659074a05

View File

@@ -12,7 +12,7 @@ pub fn day_main() {
type RiddleResult = i64; type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult { fn part1(input: &str) -> RiddleResult {
let p = Precomputed::new(2); let mut p = Precomputed::new(2);
input input
.lines() .lines()
.map(|line| p.shortest(line) * value(line)) .map(|line| p.shortest(line) * value(line))
@@ -23,14 +23,19 @@ fn value(line: &str) -> i64 {
line[0..3].parse::<i64>().unwrap() line[0..3].parse::<i64>().unwrap()
} }
fn part2(_input: &str) -> RiddleResult { fn part2(input: &str) -> RiddleResult {
0 let mut p = Precomputed::new(25);
input
.lines()
.map(|line| p.shortest(line) * value(line))
.sum()
} }
struct Precomputed { struct Precomputed {
num_sp: HashMap<(char, char), Vec<&'static str>>, num_sp: HashMap<(char, char), Vec<&'static str>>,
arrow_sp: HashMap<(char, char), Vec<&'static str>>, arrow_sp: HashMap<(char, char), Vec<&'static str>>,
robot_layers: i64, robot_layers: i64,
cache: HashMap<(char, char, i64), i64>,
} }
impl Precomputed { impl Precomputed {
@@ -41,10 +46,11 @@ impl Precomputed {
num_sp, num_sp,
arrow_sp, arrow_sp,
robot_layers, robot_layers,
cache: HashMap::new(),
} }
} }
fn shortest(&self, digit_pad: &str) -> RiddleResult { fn shortest(&mut self, digit_pad: &str) -> RiddleResult {
format!("A{digit_pad}") format!("A{digit_pad}")
.chars() .chars()
.tuple_windows() .tuple_windows()
@@ -53,6 +59,7 @@ impl Precomputed {
.num_sp .num_sp
.get(&(a, b)) .get(&(a, b))
.unwrap() .unwrap()
.clone()
.iter() .iter()
.map(|sp| format!("A{sp}A")) // we add the A in the next layer at the end of each sequence .map(|sp| format!("A{sp}A")) // we add the A in the next layer at the end of each sequence
.map(|sp| { .map(|sp| {
@@ -76,12 +83,15 @@ impl Precomputed {
.sum() .sum()
} }
fn get(&self, a: char, b: char, n: i64) -> i64 { fn get(&mut self, a: char, b: char, n: i64) -> i64 {
if n == 0 { if n == 0 {
return 1; return 1;
} }
let paths = self.arrow_sp.get(&(a, b)).unwrap(); if let Some(result) = self.cache.get(&(a, b, n)) {
paths return *result;
}
let paths = self.arrow_sp.get(&(a, b)).unwrap().clone();
let result = paths
.iter() .iter()
.map(|sp| format!("A{sp}A")) .map(|sp| format!("A{sp}A"))
.map(|sp| { .map(|sp| {
@@ -100,7 +110,9 @@ impl Precomputed {
x x
}) })
.min() .min()
.unwrap() .unwrap();
self.cache.insert((a, b, n), result);
result
} }
} }