
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Rectangle Area in C++
Suppose we want to find the total area covered by two rectilinear rectangles in a 2D plane. Here each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
To solve this, we will follow these steps −
-
if C = E or A >= G or B >= H or D <= F, then
return (C – A) * (D – B) + (G – E) * (H – F)
Define an array h, insert A, C, E, G into h
Define an array v, insert B, D, F, H into v
sort h array and sort v array
temp := (h[2] – h[1]) * (v[2] – v[1])
total := temp
total := total + (C – A) * (D – B)
total := total + (G – E) * (H – F)
return total
Example(C++)
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { if(C <= E || A >= G || B >= H || D <= F) return (C - A) * (D - B) + (G - E) * (H - F); vector <int> h; h.push_back(A); h.push_back(C); h.push_back(E); h.push_back(G); vector <int> v; v.push_back(B); v.push_back(D); v.push_back(F); v.push_back(H); sort(h.begin(), h.end()); sort(v.begin(), v.end()); long long int temp = (h[2] - h[1]) * (v[2] - v[1]); long long int total = - temp; total += (C - A) * (D - B); total += (G - E) * (H - F); return total; } }; main(){ Solution ob; cout << (ob.computeArea(-3, 0, 3, 4, 0, -1, 9, 2)); }
Input
-3 0 3 4 0 -1 9 2
Output
45
Advertisements