AoC2022/src/bin/day4.rs

54 lines
1.3 KiB
Rust

use itertools::Itertools;
use std::collections::HashSet;
use std::error::Error;
use std::fs::File;
use std::io::{self, BufRead};
use std::vec::Vec;
fn main() -> Result<(), Box<dyn Error>> {
let file = File::open("inputs/day4.txt")?;
let lines = io::BufReader::new(file).lines().map(|l| l.unwrap());
let sections: Vec<((u32, u32), (u32, u32))> = lines
.map(|l| {
l.split(',')
.map(|p| {
p.split('-')
.map(|id| id.parse::<u32>().unwrap())
.collect_tuple()
.unwrap()
})
.collect_tuple()
.unwrap()
})
.collect();
let count1 = sections
.iter()
.map(|((a, b), (x, y))| {
if (a >= x && b <= y) || (x >= a && y <= b) {
1
} else {
0
}
})
.fold(0, |a, b| a + b);
println!("Answer Part1: {}", count1);
let count2 = sections
.iter()
.map(|((a, b), (x, y))| {
if (a <= x && x <= b) || (x <= a && a <= y) {
1
} else {
0
}
})
.fold(0, |a, b| a + b);
println!("Answer Part2: {}", count2);
Ok(())
}