Form Rectangle from Triangles A rectangle shall be formed from many triangles. Given vertices of 'n' triangles ,with some triangles among them that can form a rectangle, design an algorithm and write a C++ code to determine the triangles that can form a rectangle. Print the vertices of the triangle in sorted order. That is triangles should also be sorted and the vertices in a triangle also should be sorted. A rectangle may contain four triangles as shown in figure below: For example, consider six triangles with the following vertices: Triangle 1 – (10, 6), (10, 16), (5, 6) Triangle 2 - (25, 8), (20, 4), (28, 6) Triangle 3 – (0, 6), (0, 16), (5, 6) Triangle 4 – (0, 16), (10, 16), (5, 6) Triangle 5 – (15,10), (20, 15), (25, 8) Triangle 6 – (0, 6 ), (5, 6 ), (10, 6) Triangle 1,3 and 4 can form a rectangle.
#include <bits/stdc++.h>
using namespace std;
#define NUMBER_OF_TRIANGlES 4
struct Triangles_Coordinates
{
int x1, y1;
int x2, y2;
};
int getDistance(pair<int, int> x, pair<int, int> y)
{
return (x.first - y.first)*(x.first - y.first) +
(x.second - y.second)*(x.second - y.second);
}
bool isRectangle(Triangles_Coordinates triangle[])
{
set< pair<int, int> > code;
for (int n = 0; n < NUMBER_OF_TRIANGlES; n++)
{
code.insert(make_pair(triangle[n].x1, triangle[n].y1));
code.insert(make_pair(triangle[n].x2, triangle[n].y2));
}
if (code.size() != 4)
return false;
set<int> distance_array;
for (auto x=code.begin(); x!=code.end(); x++)
for (auto y=code.begin();y!=code.end(); y++)
if (*x != *y)
distance_array.insert(getDistance(*x, *y));
if (distance_array.size() > 3)
return false;
int distances[3];
int r = 0;
for (auto code1 = distance_array.begin(); code1 != distance_array.end(); code1++)
distances[r++] = *code1;
if (distance_array.size() == 2)
return (2*distances[0] == distances[1]);
return (distances[0] + distances[1] == distances[2]);
}
int main()
{
Triangles_Coordinates triangle[] =
{
{4, 2, 7, 5},
{2, 4, 4, 2},
{2, 4, 5, 7},
{5, 7, 7, 5}
};
(isRectangle(triangle))?cout << "Yes\n":cout << "No\n";
}
Comments
Leave a comment