2018-12-03 20:25:55 +01:00
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 ::< Vec < _ > > ( ) ;
let mut rectangles : Vec < Rectangle > = Vec ::new ( ) ;
for line in lines {
let r = line . split ( | c | c = = ' ' | | c = = '@' | | c = = ',' | | c = = ':' | | c = = 'x' | | c = = '#' ) . filter_map ( | c | c . parse ::< i32 > ( ) . ok ( ) ) . collect ::< Vec < _ > > ( ) ;
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 < Rectangle > ) -> 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 ;
}
2018-12-04 03:50:26 +01:00
fn not_intersecting_claim ( rectangles : & [ Rectangle ] ) -> Result < i32 , & str >
2018-12-03 20:25:55 +01:00
{
2018-12-04 03:50:26 +01:00
' outer :
for rect1 in rectangles . iter ( ) {
for rect2 in rectangles . iter ( ) {
if rect1 . id ! = rect2 . id & & rectangles_intersecting ( & rect1 , & rect2 ) {
continue 'outer ;
}
2018-12-03 20:25:55 +01:00
}
2018-12-04 03:50:26 +01:00
return Ok ( rect1 . id . clone ( ) ) ;
2018-12-03 20:25:55 +01:00
}
2018-12-04 03:50:26 +01:00
Err ( " No not intersecting claim found " )
2018-12-03 20:25:55 +01:00
}
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 ;
}
}