Day 5 Part 2 complete

This commit is contained in:
Luke Else 2023-12-05 07:30:26 +00:00
parent 916e52783a
commit ed05221dff

View File

@ -22,9 +22,35 @@ impl Solution for Day05 {
fn part2( fn part2(
&self, &self,
_input: &mut Vec<String>, input: &mut Vec<String>,
) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> { ) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> {
Ok(Box::new("Ready")) let (seeds, maps) = self.get_mappings(input)?;
let seeds = seeds.iter()
.tuples()
.map(|(&a, len)| (a, a + len))
.collect::<Vec<_>>();
let locations = maps.iter().fold(seeds, |seeds, mappings|
seeds.iter().flat_map(|&(start, end)| {
let mut mapped = Vec::new();
let mut unmapped = vec![(start, end)];
for &(dst, src, len) in mappings {
let mut m = Vec::new();
for (start, end) in unmapped {
let a = (start, end.min(src));
let b = (start.max(src), (src+len).min(end));
let c = ((src+len).max(start), end);
if a.0 < a.1 { m.push(a); }
if b.0 < b.1 { mapped.push((b.0-src+dst, b.1-src+dst)); }
if c.0 < c.1 { m.push(c); }
}
unmapped = m;
}
mapped.extend(unmapped);
mapped
}).collect()
);
Ok(Box::new(locations.iter().map(|&(s, _)| s).min().unwrap()))
} }
fn get_day(&self) -> u8 { fn get_day(&self) -> u8 {
@ -90,6 +116,6 @@ mod test {
.unwrap() .unwrap()
.to_string(); .to_string();
assert_eq!(answer, "Ready"); assert_eq!(answer, "46");
} }
} }