Complete day 4 part 1

This commit is contained in:
Timothy Warren 2022-12-05 10:26:11 -05:00
parent 19d6fa3213
commit 983d8a7064
4 changed files with 1061 additions and 0 deletions

7
day4/Cargo.lock generated Normal file
View File

@ -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"

8
day4/Cargo.toml Normal file
View File

@ -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]

1000
day4/src/input.txt Normal file

File diff suppressed because it is too large Load Diff

46
day4/src/main.rs Normal file
View File

@ -0,0 +1,46 @@
#[derive(Debug, PartialEq, PartialOrd)]
struct Range {
low: u32,
high: u32,
}
impl From<&str> for Range {
fn from(s: &str) -> Self {
let parts: Vec<&str> = s.split("-").collect();
let low: u32 = parts[0].parse().unwrap();
let high: u32 = parts[1].parse().unwrap();
Range { low, high }
}
}
impl Range {
fn contains(&self, other: &Range) -> bool {
self.low <= other.low && self.high >= other.high
}
}
// ----------------------------------------------------------------------------
fn parse_ranges(line: &str) -> (Range, Range) {
let ranges: Vec<&str> = line.split(',').collect();
let range_a = Range::from(ranges[0]);
let range_b = Range::from(ranges[1]);
(range_a, range_b)
}
fn main() {
let file_str = include_str!("input.txt");
let count = file_str
.lines()
.map(|line| parse_ranges(line))
.map(|(range_a, range_b)| range_a.contains(&range_b) || range_b.contains(&range_a))
.filter(|contains| *contains == true)
.collect::<Vec<bool>>()
.len();
println!("Part 1: fully contained pairs: {}", count);
}