diff --git a/Cargo.lock b/Cargo.lock index fb1fc33..ecfc882 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -74,6 +74,7 @@ dependencies = [ "clap", "color-eyre", "itertools", + "rangemap", ] [[package]] @@ -297,6 +298,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rangemap" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acbbbbea733ec66275512d0b9694f34102e7d5406fdbe2ad8d21b28dce92887c" + [[package]] name = "rustc-demangle" version = "0.1.26" diff --git a/Cargo.toml b/Cargo.toml index 2491122..7f5cdee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,3 +7,4 @@ edition = "2024" clap = { version = "4.5.53", features = ["derive"] } color-eyre = "0.6.5" itertools = "0.14.0" +rangemap = "1.7.0" diff --git a/src/solutions/day_05.rs b/src/solutions/day_05.rs index e07968a..7e66f5e 100644 --- a/src/solutions/day_05.rs +++ b/src/solutions/day_05.rs @@ -1,20 +1,10 @@ -use std::collections::BTreeMap; +use rangemap::RangeInclusiveSet; use crate::solution::Solution; -#[derive(Clone, Copy, Debug)] -struct Range(u64, u64); - -impl Range { - fn parse(line: &str) -> Self { - let (from, to) = line.split_once('-').unwrap(); - Self(from.parse().unwrap(), to.parse().unwrap()) - } -} - #[derive(Debug)] pub struct Day05 { - ranges: Vec, + ranges: RangeInclusiveSet, ingredients: Vec, } @@ -22,7 +12,13 @@ impl Solution for Day05 { fn with_input(input: String) -> Self { let (ranges, ingredients) = input.split_once("\n\n").unwrap(); - let ranges = ranges.lines().map(Range::parse).collect(); + let ranges = ranges + .lines() + .map(|line| { + let (from, to) = line.split_once('-').unwrap(); + from.parse().unwrap()..=to.parse().unwrap() + }) + .collect(); let ingredients = ingredients.lines().map(|l| l.parse().unwrap()).collect(); Self { @@ -32,19 +28,10 @@ impl Solution for Day05 { } fn part1(&self) -> String { - let mut ingredients_map = self - .ingredients + self.ingredients .iter() - .copied() - .map(|i| (i, false)) - .collect::>(); - - for Range(from, to) in &self.ranges { - for (_, is_fresh) in ingredients_map.range_mut(from..=to) { - *is_fresh = true; - } - } - - ingredients_map.values().filter(|v| **v).count().to_string() + .filter(|i| self.ranges.contains(i)) + .count() + .to_string() } }