Compare commits

..

2 Commits

Author SHA1 Message Date
MasterofJOKers 93e88b94b7 day04: Change implementation for part 2
This will print all overlapping ranges instead of only fully contained
ranges.
2022-12-18 16:55:34 +01:00
MasterofJOKers 57b95e8c2c 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-12-18 16:52:45 +01:00
3 changed files with 40 additions and 0 deletions

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

8
day04/Cargo.toml Normal file
View File

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

25
day04/src/main.rs Normal file
View File

@ -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 {} overlapping ranges.", count);
Ok(())
}