This commit is contained in:
JonOfUs 2022-12-04 18:45:22 +01:00
parent d409ced72d
commit e3e713f0cd
3 changed files with 1112 additions and 2 deletions

1000
res/04/input.txt Normal file

File diff suppressed because it is too large Load diff

110
src/d04.rs Normal file
View file

@ -0,0 +1,110 @@
use std::fs;
pub fn d04() {
let path = "res/04/input.txt";
let contents = fs::read_to_string(path).expect("I/O error, wrong path?");
let cont_arr = contents.split("\n");
// Parse pairs
let pairs: Vec<Pair> = cont_arr
.filter(|line| *line != "")
.map(|line| {
let elves: Vec<&str> = line.split(",").collect();
let elf1: Vec<&str> = elves[0].split("-").collect();
let elf2: Vec<&str> = elves[1].split("-").collect();
Pair::new(
elf1[0].parse::<i32>().unwrap(),
elf1[1].parse::<i32>().unwrap(),
elf2[0].parse::<i32>().unwrap(),
elf2[1].parse::<i32>().unwrap(),
)
})
.collect();
// Calculate contained sections (task 1)
let res: i32 = pairs
.iter()
.map(|p| {
if p.is_contained() {
return 1;
} else {
return 0;
}
})
.sum();
println!("Result 1: {}", res);
// Calculate overlapping sections (task 2)
let res: i32 = pairs
.iter()
.map(|p| {
if p.overlaps() {
return 1;
} else {
return 0;
}
})
.sum();
println!("Result 2: {}", res);
}
// Pair of 2 ID sections
struct Pair {
pub x: Section,
pub y: Section,
}
impl Pair {
pub fn new(x1: i32, x2: i32, y1: i32, y2: i32) -> Self {
Pair {
x: Section { begin: x1, end: x2 },
y: Section { begin: y1, end: y2 },
}
}
// checks whether one of the sections is contained in each other
pub fn is_contained(&self) -> bool {
self.x.contains(&self.y) || self.y.contains(&self.x)
}
// checks whether the two sections overlap at >=1 IDs
pub fn overlaps(&self) -> bool {
Section::overlaps(&self.x, &self.y)
}
}
// ID section containing the beginning and the end ID
struct Section {
pub begin: i32,
pub end: i32,
}
impl Section {
// checks whether the passed section is fully contained in this section
pub fn contains(&self, other: &Section) -> bool {
self.begin <= other.begin && self.end >= other.end
}
// checks whether the two passed sections overlap at >=1 IDs
pub fn overlaps(s1: &Section, s2: &Section) -> bool {
if s1.begin >= s2.begin && s1.begin <= s2.end {
return true;
}
if s1.end >= s2.begin && s1.end <= s2.end {
return true;
}
if s2.begin >= s1.begin && s2.begin <= s1.end {
return true;
}
if s2.end >= s1.begin && s2.end <= s1.end {
return true;
}
false
}
}

View file

@ -1,5 +1,5 @@
mod d03;
mod d04;
fn main() {
d03::d03();
d04::d04();
}