From c93e15720de529fba6d73f1f9bbf45f391698c5f Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Sun, 4 Dec 2022 19:02:40 +0100 Subject: [PATCH] Day 4 --- src/day04.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 7 +++++++ 2 files changed, 61 insertions(+) create mode 100644 src/day04.rs diff --git a/src/day04.rs b/src/day04.rs new file mode 100644 index 0000000..42302fd --- /dev/null +++ b/src/day04.rs @@ -0,0 +1,54 @@ +use regex::Regex; + +type Pair = ((i32, i32), (i32, i32)); + +pub fn parse(s: &str) -> Vec { + let mut sections = Vec::new(); + let r = Regex::new(r"^(\d+)-(\d+),(\d+)-(\d+)$").unwrap(); + for l in s.lines() { + let cap = r.captures(l).unwrap(); + sections.push(((cap[1].parse::().unwrap(), cap[2].parse::().unwrap()), (cap[3].parse::().unwrap(), cap[4].parse::().unwrap()))); + } + return sections; +} + +pub fn number_fully_contain(pairs: &[Pair]) -> i32 { + pairs.iter().filter_map(|((a1, a2), (b1, b2))| { + if a1 <= b1 && a2 >= b2 || b1 <= a1 && b2 >= a2 { Some(1) } else { None } + }).sum() +} + +pub fn number_overlaps(pairs: &[Pair]) -> i32 { + pairs.iter().filter_map(|((a1, a2), (b1, b2))| { + if a2 >= b1 && a1 <= b2 { Some(1) } else { None } + }).sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn part1() { + let pairs ="2-4,6-8 +2-3,4-5 +5-7,7-9 +2-8,3-7 +6-6,4-6 +2-6,4-8"; + + assert_eq!(number_fully_contain(&parse(pairs)), 2); + } + + #[test] + fn part2() { + let pairs ="2-4,6-8 +2-3,4-5 +5-7,7-9 +2-8,3-7 +6-6,4-6 +2-6,4-8"; + + assert_eq!(number_overlaps(&parse(pairs)), 4); + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index e7b4bed..014c31d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ mod common; mod day01; mod day02; mod day03; +mod day04; fn day01() -> String { let f = fs::File::open("data/day01.input").unwrap(); @@ -24,6 +25,11 @@ fn day03() -> String { format!("part1: {}, part2: {}", day03::priority_sum(&rucksacks), day03::badge_sum(&rucksacks)) } +fn day04() -> String { + let pairs = day04::parse(&fs::read_to_string("data/day04.input").unwrap()); + format!("part1: {}, part2: {}", day04::number_fully_contain(&pairs), day04::number_overlaps(&pairs)) +} + fn format_micros(t: u128) -> String { if t < 10_000 { format!("{} μs", t) @@ -46,6 +52,7 @@ fn main() { day01, day02, day03, + day04, ); let args: Vec = env::args().skip(1).collect(); -- 2.45.2