This commit is contained in:
2025-12-05 18:36:02 +00:00
parent 8c41171fa9
commit 71954ac209
4 changed files with 1286 additions and 0 deletions

View File

@@ -19,5 +19,9 @@ path = "src/day3/main.rs"
name = "day4"
path = "src/day4/main.rs"
[[bin]]
name = "day5"
path = "src/day5/main.rs"
[dependencies]
anyhow = "1.0.100"

1187
src/day5/act.txt Normal file

File diff suppressed because it is too large Load Diff

84
src/day5/main.rs Normal file
View File

@@ -0,0 +1,84 @@
use anyhow::Result;
use std::{fs, ops::RangeInclusive};
trait Extend<T> {
fn extend(&self, other: &T) -> Option<T>;
}
impl Extend<RangeInclusive<u64>> for RangeInclusive<u64> {
fn extend(&self, other: &RangeInclusive<u64>) -> Option<RangeInclusive<u64>> {
if other.contains(self.start()) && other.contains(self.end()) {
return Some(other.clone());
} else if self.contains(other.start()) && self.contains(other.end()) {
return Some((*self).clone());
} else if self.contains(other.start()) {
return Some(*self.start()..=*other.end());
} else if self.contains(other.end()) {
return Some(*other.start()..=*self.end());
}
return None;
}
}
fn main() -> Result<()> {
let text = fs::read_to_string("src/day5/act.txt")?;
let mut valid_ids: Vec<Option<RangeInclusive<u64>>> = text
.split("\n")
.take_while(|s| s.len() > 0)
.map(|s| {
let mut v = s.split('-').map(|a| a.parse().unwrap());
let start: u64 = v.next().unwrap();
let end: u64 = v.next().unwrap();
return Some(start..=end);
})
.collect();
let mut expanded = true;
while expanded {
expanded = false;
for i in 0..valid_ids.len() {
let range_to_extend = &valid_ids[i];
if range_to_extend.is_some() {
let mut range_to_extend = valid_ids[i].as_ref().unwrap().clone();
for j in (i + 1)..valid_ids.len() {
if let Some(maybe_comp) = valid_ids[j].as_ref() {
if let Some(extended) = range_to_extend.extend(&maybe_comp) {
println!(
"{:?} expanded by {:?} into {:?}",
range_to_extend, maybe_comp, extended
);
expanded = true;
range_to_extend = extended;
valid_ids[j] = None;
}
}
}
valid_ids[i] = Some(range_to_extend);
}
}
valid_ids = valid_ids.into_iter().filter(|a| a.is_some()).collect();
}
let valid_ids = valid_ids.into_iter().map(|a| a.unwrap());
valid_ids.clone().for_each(|a| println!("{:?}", a));
let ids_to_check = text
.split("\n")
.skip_while(|s| s.len() > 0)
.skip(1)
.filter(|s| s.len() > 0)
.fold(0, |sum, line| {
let i: u64 = line.parse().unwrap();
sum + valid_ids.clone().any(|range| range.contains(&i)) as i64
});
let num_valid_ids = valid_ids.fold(0, |sum, range_id| {
sum + range_id.end() - range_id.start() + 1
});
println!("sol1: {}! sol2: {}", ids_to_check, num_valid_ids);
Ok(())
}

11
src/day5/test.txt Normal file
View File

@@ -0,0 +1,11 @@
3-5
10-14
16-20
12-18
1
5
8
11
17
32