diff options
author | Jesse Luehrs <doy@tozt.net> | 2022-12-11 21:59:21 -0500 |
---|---|---|
committer | Jesse Luehrs <doy@tozt.net> | 2022-12-11 22:16:30 -0500 |
commit | e2d219b331a878bbb3c9dcef9ea4e218b2e3ee06 (patch) | |
tree | 93e418011c45cab8d4070d3d33b377a9364f4a27 /src/bin/2022/day4.rs | |
parent | 179467096141b7e8f67d63b89fd21e779a564fe6 (diff) | |
download | advent-of-code-e2d219b331a878bbb3c9dcef9ea4e218b2e3ee06.tar.gz advent-of-code-e2d219b331a878bbb3c9dcef9ea4e218b2e3ee06.zip |
refactor
Diffstat (limited to 'src/bin/2022/day4.rs')
-rw-r--r-- | src/bin/2022/day4.rs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/bin/2022/day4.rs b/src/bin/2022/day4.rs new file mode 100644 index 0000000..2fe98c5 --- /dev/null +++ b/src/bin/2022/day4.rs @@ -0,0 +1,69 @@ +#![allow(dead_code)] +#![allow(unused_variables)] + +use advent_of_code::prelude::*; + +pub struct Pair { + first: (i64, i64), + second: (i64, i64), +} + +impl Pair { + fn contains(&self) -> bool { + range_contains(self.first, self.second) + || range_contains(self.second, self.first) + } + + fn overlaps(&self) -> bool { + range_overlaps(self.first, self.second) + || range_overlaps(self.second, self.first) + } +} + +fn range_contains(a: (i64, i64), b: (i64, i64)) -> bool { + (a.0..=a.1).contains(&b.0) && (a.0..=a.1).contains(&b.1) +} + +fn range_overlaps(a: (i64, i64), b: (i64, i64)) -> bool { + (a.0..=a.1).contains(&b.0) || (a.0..=a.1).contains(&b.1) +} + +pub fn parse(fh: File) -> Result<impl Iterator<Item = Pair>> { + Ok(parse::raw_lines(fh).map(|line| { + let mut parts = line.split(','); + let first = parts.next().unwrap(); + let mut first_parts = first.split('-'); + let second = parts.next().unwrap(); + let mut second_parts = second.split('-'); + Pair { + first: ( + first_parts.next().unwrap().parse().unwrap(), + first_parts.next().unwrap().parse().unwrap(), + ), + second: ( + second_parts.next().unwrap().parse().unwrap(), + second_parts.next().unwrap().parse().unwrap(), + ), + } + })) +} + +pub fn part1(pairs: impl Iterator<Item = Pair>) -> Result<usize> { + Ok(pairs.filter(|pair| pair.contains()).count()) +} + +pub fn part2(pairs: impl Iterator<Item = Pair>) -> Result<usize> { + Ok(pairs.filter(|pair| pair.overlaps()).count()) +} + +#[test] +fn test() { + assert_eq!( + part1(parse(parse::data(2022, 4).unwrap()).unwrap()).unwrap(), + 515 + ); + assert_eq!( + part2(parse(parse::data(2022, 4).unwrap()).unwrap()).unwrap(), + 883 + ); +} |