Add second approach using reverse search

This commit is contained in:
2023-12-05 13:35:52 +01:00
committed by Hannes Körber
parent f4b8d4108c
commit ac8799aefb

View File

@@ -109,6 +109,15 @@ impl Map {
None None
} }
} }
fn map_reverse(&self, value: usize) -> Option<usize> {
if self.destination_range.contains(&value) {
let index = value - self.destination_range.start;
Some(self.source_range.clone().nth(index).unwrap())
} else {
None
}
}
} }
#[derive(Debug)] #[derive(Debug)]
@@ -142,6 +151,15 @@ impl MapList {
} }
value value
} }
fn map_reverse(&self, value: usize) -> usize {
for map in &self.maps {
if let Some(mapped_value) = map.map_reverse(value) {
return mapped_value;
}
}
value
}
} }
fn part1(input: &str) -> Result<usize, String> { fn part1(input: &str) -> Result<usize, String> {
@@ -169,7 +187,36 @@ fn part2(input: &str) -> Result<usize, String> {
println!("parsing rest found: {rest}"); println!("parsing rest found: {rest}");
panic!(); panic!();
} }
let lowest_location = almanac
#[derive(PartialEq, Eq)]
#[allow(dead_code)]
enum Approach {
Reverse,
BruteForce,
}
let approach = Approach::BruteForce;
let lowest_location = match approach {
Approach::Reverse => {
let mut i = 0;
loop {
let mut reverse_val = i;
for map_list in almanac.map_lists.iter().rev() {
reverse_val = map_list.map_reverse(reverse_val);
}
if almanac
.seeds
.0
.iter()
.any(|seed| seed.contains(&reverse_val))
{
break i;
}
i += 1;
}
}
Approach::BruteForce => almanac
.seeds .seeds
.0 .0
.into_par_iter() .into_par_iter()
@@ -191,7 +238,9 @@ fn part2(input: &str) -> Result<usize, String> {
result result
}) })
.min() .min()
.unwrap(); .unwrap(),
};
Ok(lowest_location) Ok(lowest_location)
} }