day 4. cruisin

master
Dustin Swan 2 years ago
parent a502096736
commit a468a9b122
Signed by: dustinswan
GPG Key ID: AB49BD6B2B3A6377

7
day4/Cargo.lock generated

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day4"
version = "0.1.0"

@ -0,0 +1,8 @@
[package]
name = "day4"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

File diff suppressed because it is too large Load Diff

@ -0,0 +1,55 @@
#[derive(Debug)]
struct Assignment {
left: (u32, u32),
right: (u32, u32),
}
fn main() {
let contents = std::fs::read_to_string("data.txt").expect("Failed to read file");
let lines: Vec<&str> = contents.lines().collect();
let assignments: Vec<Assignment> = lines.iter().map(|x| parse_line(&x)).collect();
// Part 1
let num_contained: usize = assignments
.iter()
.map(|a| any_fully_contained(&a))
.filter(|&x| x)
.collect::<Vec<bool>>()
.len();
println!("Number fully contained: {:?}", num_contained);
// Part 2
let num_overlap: usize = assignments
.iter()
.map(|a| any_overlap(&a))
.filter(|&x| x)
.collect::<Vec<bool>>()
.len();
println!("Number overlapping: {:?}", num_overlap);
}
fn parse_line(l: &str) -> Assignment {
let parts: Vec<&str> = l.split(',').collect();
let pairs: Vec<Vec<&str>> = parts.iter().map(|x| x.split('-').collect()).collect();
let pairs: Vec<Vec<u32>> = pairs // map to u32
.iter()
.map(|x| x.iter().map(|y| y.parse().unwrap()).collect())
.collect();
Assignment {
left: (pairs[0][0], pairs[0][1]),
right: (pairs[1][0], pairs[1][1]),
}
}
fn any_fully_contained(a: &Assignment) -> bool {
(a.left.0 <= a.right.0 && a.left.1 >= a.right.1) || // left fully contains right
(a.right.0 <= a.left.0 && a.right.1 >= a.left.1) // or right fully contains left
}
fn any_overlap(a: &Assignment) -> bool {
(a.left.0 >= a.right.0 && a.left.0 <= a.right.1)
|| (a.left.1 >= a.right.0 && a.left.1 <= a.right.1)
|| (a.right.0 >= a.left.0 && a.right.0 <= a.left.1)
|| (a.right.1 >= a.left.0 && a.right.1 <= a.left.1)
}

@ -0,0 +1,6 @@
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
Loading…
Cancel
Save