You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.4 KiB
Rust
70 lines
1.4 KiB
Rust
use crate::util::prelude::*;
|
|
|
|
static INPUT: &str = include_str!("inputs/day4.txt");
|
|
|
|
fn parse_range(s: &str) -> core::ops::RangeInclusive<uint> {
|
|
let mut parts = s.split('-');
|
|
let lo = parts.next().unwrap();
|
|
let hi = parts.next().unwrap();
|
|
|
|
let lo = lo.parse().unwrap();
|
|
let hi = hi.parse().unwrap();
|
|
|
|
lo..=hi
|
|
}
|
|
|
|
fn fully_contains<U: PartialOrd>(
|
|
haystack: &core::ops::RangeInclusive<U>,
|
|
needle: &core::ops::RangeInclusive<U>,
|
|
) -> bool {
|
|
haystack.contains(needle.start()) && haystack.contains(needle.end())
|
|
}
|
|
|
|
fn has_overlap<U: PartialOrd>(
|
|
a: &core::ops::RangeInclusive<U>,
|
|
b: &core::ops::RangeInclusive<U>,
|
|
) -> bool {
|
|
a.contains(b.start())
|
|
|| a.contains(b.end())
|
|
|| b.contains(a.start())
|
|
|| b.contains(a.end())
|
|
}
|
|
|
|
pub fn part1() {
|
|
let sum = INPUT
|
|
.split('\n')
|
|
.filter(|s| !s.is_empty())
|
|
.map(|line| {
|
|
let mut elves = line.split(',');
|
|
let fst = elves.next().unwrap();
|
|
let fst = parse_range(fst);
|
|
|
|
let snd = elves.next().unwrap();
|
|
let snd = parse_range(snd);
|
|
|
|
u64::from(fully_contains(&fst, &snd) || fully_contains(&snd, &fst))
|
|
})
|
|
.sum::<uint>();
|
|
|
|
println!("{}", sum);
|
|
}
|
|
|
|
pub fn part2() {
|
|
let sum = INPUT
|
|
.split('\n')
|
|
.filter(|s| !s.is_empty())
|
|
.map(|line| {
|
|
let mut elves = line.split(',');
|
|
let fst = elves.next().unwrap();
|
|
let fst = parse_range(fst);
|
|
|
|
let snd = elves.next().unwrap();
|
|
let snd = parse_range(snd);
|
|
|
|
u64::from(has_overlap(&fst, &snd))
|
|
})
|
|
.sum::<uint>();
|
|
|
|
println!("{}", sum);
|
|
}
|