Perimeter of the Union of Two Rectangles | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool doIntersect ( vector < int > X , vector < 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 ; } int getUnionPerimeter ( vector < int > X , vector < int > Y ) { int perimeter = 0 ; if ( ! doIntersect ( X , Y ) ) { perimeter += 2 * ( abs ( X [ 1 ] - X [ 0 ] ) + abs ( Y [ 1 ] - Y [ 0 ] ) ) ; perimeter += 2 * ( abs ( X [ 3 ] - X [ 2 ] ) + abs ( Y [ 3 ] - Y [ 2 ] ) ) ; } else { int w = * max_element ( X . begin ( ) , X . end ( ) ) - * min_element ( X . begin ( ) , X . end ( ) ) ; int l = * max_element ( Y . begin ( ) , Y . end ( ) ) - * min_element ( Y . begin ( ) , Y . end ( ) ) ; perimeter = 2 * ( l + w ) ; } return perimeter ; } int main ( ) { vector < int > X { -1 , 2 , 4 , 6 } ; vector < int > Y { 2 , 5 , 3 , 7 } ; cout << getUnionPerimeter ( X , Y ) ; }