Perimeter of the Union of Two Rectangles | Java program for the above approach ; Function to check if two rectangles are intersecting or not ; If one rectangle is to the right of other 's right edge ; If one rectangle is on the top of other 's top edge ; Function to return the perimeter of the Union of Two Rectangles ; Stores the resultant perimeter ; If rectangles do not interesect ; Perimeter of Rectangle 1 ; Perimeter of Rectangle 2 ; If the rectangles intersect ; Get width of combined figure ; Get length of combined figure ; Return the perimeter ; Driver Code
import java . util . * ; class GFG { static boolean doIntersect ( int [ ] X , int [ ] Y ) { if ( X [ 0 ] > X [ 3 ] X [ 2 ] > X [ 1 ] ) return false ; if ( Y [ 0 ] > Y [ 3 ] Y [ 2 ] > Y [ 1 ] ) return false ; return true ; } static int getUnionPerimeter ( int [ ] X , int [ ] Y ) { int perimeter = 0 ; if ( ! doIntersect ( X , Y ) ) { perimeter += 2 * ( Math . abs ( X [ 1 ] - X [ 0 ] ) + Math . abs ( Y [ 1 ] - Y [ 0 ] ) ) ; perimeter += 2 * ( Math . abs ( X [ 3 ] - X [ 2 ] ) + Math . abs ( Y [ 3 ] - Y [ 2 ] ) ) ; } else { int w = Arrays . stream ( X ) . max ( ) . getAsInt ( ) - Arrays . stream ( X ) . min ( ) . getAsInt ( ) ; int l = Arrays . stream ( Y ) . max ( ) . getAsInt ( ) - Arrays . stream ( Y ) . min ( ) . getAsInt ( ) ; perimeter = 2 * ( l + w ) ; } return perimeter ; } public static void main ( String [ ] args ) { int [ ] X = { - 1 , 2 , 4 , 6 } ; int [ ] Y = { 2 , 5 , 3 , 7 } ; System . out . print ( getUnionPerimeter ( X , Y ) ) ; } }