Advent of Code 2022, Day 4 -- Camp Cleanup
Rust solutions to Advent of Code 2022, day 4.
It is time for Advent of Code day 4! I've officially solved more problems in Rust this year than last year (made it to day 3).
Today's challenge looks complicated, but really, it's just comparing numbers.
Full code for Day 4 can be found on Github.
The Day 4 problem can be found at adventofcode.com/2022/day/4.
Note: This post currently just has my solution code. I'll update it with a breakdown as soon as I can.
Jump to:
My final full code:
use std::fs;
#[derive(Debug)]
struct Assignment {
start: u32,
end: u32,
}
fn main() {
let input = fs::read_to_string("input.txt").unwrap();
let arr = input.split_terminator("\n").collect::<Vec<&str>>();
let contains = find_contained_assignments(
split_chores(arr.clone())
);
println!("{} assignment pairs contain another assignment pair.", contains);
let overlaps = find_overlaps(
split_chores(arr)
);
println!("{} assignment pairs overlap.", overlaps);
}
fn split_chores(chores: Vec<&str>) -> Vec<Vec<Assignment>> {
chores.iter().map(|chore| {
return chore.split(",").map(|assignment| {
let a = assignment
.split("-")
.collect::<Vec<&str>>();
return Assignment {
start: a[0].parse::<u32>().unwrap(),
end: a[1].parse::<u32>().unwrap(),
};
}).collect::<Vec<Assignment>>()
}).collect::<Vec<Vec<Assignment>>>()
}
fn find_contained_assignments(assignments: Vec<Vec<Assignment>>) -> usize {
assignments.into_iter().filter(|a| {
return a[0].start <= a[1].start && a[0].end >= a[1].end ||
a[1].start <= a[0].start && a[1].end >= a[0].end;
}).collect::<Vec<Vec<Assignment>>>().len()
}
fn find_overlaps(assignments: Vec<Vec<Assignment>>) -> usize {
assignments.into_iter().filter(|a| {
return a[0].start >= a[1].start && a[0].start <= a[1].end ||
a[0].end >= a[1].start && a[0].end <= a[1].end ||
a[1].start >= a[0].start && a[1].start <= a[0].end ||
a[1].end >= a[0].start && a[1].start <= a[0].end;
}).collect::<Vec<Vec<Assignment>>>().len()
Part 1
TBA
Part 2
TBA
What I learned
TBA