use std::fs::File; use std::io::Read; use std::cmp; use std::collections::HashMap; struct Rectangle { id: i32, x: i32, y: i32, width: i32, height: i32, } fn main() { let mut f = File::open("input").expect("file not found"); let mut contents = String::new(); f.read_to_string(&mut contents).expect("something went wrong reading the file"); let lines = contents.lines().collect::>(); let mut rectangles: Vec = Vec::new(); for line in lines { let r = line.split(|c| c == ' ' || c == '@' || c == ',' || c == ':' || c == 'x' || c == '#').filter_map(|c| c.parse::().ok()).collect::>(); rectangles.push(Rectangle { id: r[0], x: r[1], y: r[2], width: r[3], height: r[4] }); } println!("{}", intersecting_area(&rectangles)); let claim; match not_intersecting_claim(&rectangles){ Ok(s) => claim = s.to_string(), Err(s) => claim = s.to_string(), } println!("{}", claim); } fn intersecting_area(rectangles: &Vec) -> i32 { let mut intersects = HashMap::new(); for rectangle in rectangles { for x in rectangle.x..rectangle.x + rectangle.width { for y in rectangle.y..rectangle.y + rectangle.height { *intersects.entry((x, y)).or_insert(0) += 1; } } } return intersects.values().filter(|i| **i > 1).count() as i32; } fn not_intersecting_claim(rectangles: &Vec) -> Result { for i in 0..rectangles.len() { let mut found = true; for j in 0..rectangles.len() { if rectangles_intersecting(&rectangles[i], &rectangles[j]) && i != j { found = false; break; } } if found { return Ok(rectangles[i].id.clone()); } } return Err(std::io::Error::new(std::io::ErrorKind::Other, "No not intersecting claim found")) } fn rectangles_intersecting(r1: &Rectangle, r2: &Rectangle) -> bool { let si = cmp::max(0, cmp::min(r1.x + r1.width, r2.x + r2.width) - cmp::max(r1.x, r2.x)) * cmp::max(0, cmp::min(r1.y + r1.height, r2.y + r2.height) - cmp::max(r1.y, r2.y)); if si > 0{ return true; } else { return false; } }