Initial commit
This commit is contained in:
68
src/day4/main.rs
Normal file
68
src/day4/main.rs
Normal file
@ -0,0 +1,68 @@
|
||||
use std::fs::read_to_string;
|
||||
|
||||
struct Range {
|
||||
start: u32,
|
||||
end: u32
|
||||
}
|
||||
|
||||
impl Range {
|
||||
fn new(start: u32 , end: u32) -> Self{
|
||||
Range {start, end}
|
||||
}
|
||||
|
||||
fn contains(&self, number: u32) -> bool {
|
||||
number >= self.start && number <= self.end
|
||||
}
|
||||
|
||||
fn fully_overlap(&self, other: &Range) -> bool {
|
||||
self.contains(other.start) && self.contains(other.end)
|
||||
}
|
||||
|
||||
fn partly_overlap(&self, other: &Range) -> bool {
|
||||
self.contains(other.start) || self.contains(other.end)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let input = read_to_string("day4.txt").unwrap();
|
||||
|
||||
let count = input
|
||||
.split_whitespace()
|
||||
.flat_map(|line| line.split(","))
|
||||
.flat_map(|line_range| line_range.split("-"))
|
||||
.map(|number| number.parse::<u32>().unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
.chunks_exact(2)
|
||||
.map(|chunk| Range::new(chunk[0], chunk[1]))
|
||||
.collect::<Vec<_>>()
|
||||
.chunks_exact(2)
|
||||
.filter_map(|range_pair|{
|
||||
if range_pair[0].fully_overlap(&range_pair[1]) || range_pair[1].fully_overlap(&range_pair[0]) {
|
||||
Some(())
|
||||
}
|
||||
else { None }
|
||||
})
|
||||
.count();
|
||||
|
||||
println!("Task1: {count}");
|
||||
|
||||
let count = input
|
||||
.split_whitespace()
|
||||
.flat_map(|line| line.split(","))
|
||||
.flat_map(|line_range| line_range.split("-"))
|
||||
.map(|number| number.parse::<u32>().unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
.chunks_exact(2)
|
||||
.map(|chunk| Range::new(chunk[0], chunk[1]))
|
||||
.collect::<Vec<_>>()
|
||||
.chunks_exact(2)
|
||||
.filter_map(|range_pair|{
|
||||
if range_pair[0].partly_overlap(&range_pair[1]) || range_pair[1].partly_overlap(&range_pair[0]) {
|
||||
Some(())
|
||||
}
|
||||
else { None }
|
||||
})
|
||||
.count();
|
||||
|
||||
println!("Task2: {count}");
|
||||
}
|
Reference in New Issue
Block a user