Created
December 5, 2023 08:10
-
-
Save tbarusseau/00aac7ab16c9251a3de1c9105c4bad60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug)] | |
struct Rules { | |
seeds: Vec<i64>, | |
maps: Vec<Vec<(i64, i64, i64)>>, | |
} | |
impl Rules { | |
fn compute_next_location(n: i64, map: &(i64, i64, i64)) -> Option<i64> { | |
let (dest_range, source_range, range_length) = *map; | |
if n >= source_range && n < source_range + range_length { | |
Some(n - source_range + dest_range) | |
} else { | |
None | |
} | |
} | |
fn compute_final_location(&self, n: i64) -> i64 { | |
self.maps.iter().fold(n, |acc, map| { | |
for l in map { | |
if let Some(v) = Self::compute_next_location(acc, l) { | |
return v; | |
} | |
} | |
acc | |
}) | |
} | |
} | |
fn process_input(input: &str) -> Rules { | |
let mut seeds = vec![]; | |
let mut maps: Vec<Vec<(i64, i64, i64)>> = vec![]; | |
let mut temp_map: Vec<(i64, i64, i64)> = vec![]; | |
for l in input.trim_end().lines().filter(|s| !s.is_empty()) { | |
if l.starts_with("seeds: ") { | |
seeds = l.split(' ').skip(1).flat_map(str::parse).collect_vec(); | |
continue; | |
} | |
if l.contains(':') { | |
if !temp_map.is_empty() { | |
maps.push(temp_map); | |
temp_map = vec![]; | |
} | |
continue; | |
} | |
temp_map.push( | |
l.split(' ') | |
.flat_map(str::parse::<i64>) | |
.collect_tuple() | |
.unwrap(), | |
); | |
} | |
if !temp_map.is_empty() { | |
maps.push(temp_map); | |
} | |
Rules { seeds, maps } | |
} | |
fn solve_part1(input: &str) -> Box<dyn std::fmt::Display> { | |
let input = process_input(input); | |
let res = input | |
.seeds | |
.iter() | |
.map(|n| input.compute_final_location(*n)) | |
.inspect(|n| println!("{n}")) | |
.min() | |
.unwrap(); | |
Box::new(res) | |
} | |
fn solve_part2(input: &str) -> Box<dyn std::fmt::Display> { | |
let input = process_input(input); | |
let mut min = i64::MAX; | |
for mut chunk in &input.seeds.iter().chunks(2) { | |
let &start = chunk.next().unwrap(); | |
let &length = chunk.next().unwrap(); | |
let end = start + length; | |
for seed in start..end { | |
min = min.min(input.compute_final_location(seed)); | |
} | |
} | |
Box::new(min) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment