day04: Add part 1

I'm not sure why this is so much to write. It feels like there should be
a more generic way to check this instead of duplicating those lines, but
maybe it's not worth it for 2 ranges ...
2022
MasterofJOKers 1 year ago
parent 6dfb583345
commit 57b95e8c2c

7
day04/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 = "day04"
version = "0.1.0"

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

@ -0,0 +1,25 @@
use std::error;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::ops;
fn main() -> Result<(), Box<dyn error::Error>> {
let f = File::open("input.txt")?;
let reader = BufReader::new(f);
let mut count: u32 = 0;
for line in reader.lines() {
let line = line?;
let range_strs = line.split(",").collect::<Vec<&str>>();
let range_a_u32 = range_strs[0].split("-").map(|x| x.parse::<u32>().unwrap()).collect::<Vec<u32>>();
let range_a = ops::Range { start: range_a_u32[0], end: range_a_u32[1] + 1 };
let range_b_u32 = range_strs[1].split("-").map(|x| x.parse::<u32>().unwrap()).collect::<Vec<u32>>();
let range_b = ops::Range { start: range_b_u32[0], end: range_b_u32[1] + 1 };
if (range_a.contains(&range_b.start) && range_a.contains(&(range_b.end - 1))) || (range_b.contains(&range_a.start) && range_b.contains(&(range_a.end - 1))) {
count += 1;
}
}
println!("Found {} completely contained ranges.", count);
Ok(())
}
Loading…
Cancel
Save