# Find Four points such that they form a square whose sides are parallel to x and y axes in Python

Suppose we have n pair of points; we have to find four points so that they can generate a square whose sides are parallel to x and y axes otherwise return "not possible" If we can find more than one square then select the one with whose area is maximum.

So, if the input is like n = 6, points = [(2, 2), (5, 5), (4, 5), (5, 4), (2, 5), (5, 2)], then the output will be 3, points are (2, 2) (5, 2) (2, 5) (5, 5)

To solve this, we will follow these steps −

• my_map := a new map

• for i in range 0 to n, do

• my_map[(points[i,0], points[i,1])] = my_map.[(points[i,0], points[i,1]], 0) + 1

• side := -1

• x := -1

• y := -1

• for i in range 0 to n, do

• my_map[points[i, 0], points[i, 1]] := my_map[points[i, 0], points[i, 1]] - 1

• for j in range 0 to n, do

• my_map[points[j, 0], points[j, 1]] := my_map[points[j, 0], points[j, 1]] - 1

• if (i is not same as j and (points[i,0]-points[j,0]) is same as (points[i,1]- points[j,1])), then

• if my_map[(points[i,0], points[j, 1])] > 0 and my_map[(points[j,0], points[i,1])] > 0, then

• if (side < |points[i,0] - points[j,0]| or (side is same as |points[i,0] - points[j,0]| and ((points[i,0] * points[i,0] + points[i,1] * points[i,1]) < (x * x + y * y)))) −

• x := points[i, 0]

• y := points[i, 1]

• side := |points[i,0] - points[j,0]|

• my_map[points[j, 0], points[j, 1]] := my_map[points[j, 0], points[j, 1]] + 1

• my_map[points[i, 0], points[i, 1]] := my_map[points[i, 0], points[i, 1]] + 1

• if side is not same as -1, then

• display side

• display points (x,y), (x+side, y), (x,y + side), (x+side, y+side)

• otherwise,

• display "No such square"

## Example

Let us see the following implementation to get better understanding −

Live Demo

def get_square_points(points,n):
my_map = dict()
for i in range(n):
my_map[(points[i][0], points[i][1])] = my_map.get((points[i][0], points[i][1]), 0) + 1
side = -1
x = -1
y = -1
for i in range(n):
my_map[(points[i][0], points[i][1])]-=1
for j in range(n):
my_map[(points[j][0], points[j][1])]-=1
if (i != j and (points[i][0]-points[j][0]) == (points[i][1]-points[j][1])):
if (my_map[(points[i][0], points[j][1])] > 0 and my_map[(points[j][0], points[i][1])] > 0):
if (side < abs(points[i][0] - points[j][0]) or (side == abs(points[i][0] - points[j][0]) and ((points[i][0] * points[i][0] + points[i][1] * points[i][1]) < (x * x + y * y)))):
x = points[i][0]
y = points[i][1]
side = abs(points[i][0] - points[j][0])
my_map[(points[j][0], points[j][1])] += 1
my_map[(points[i][0], points[i][1])] += 1
if (side != -1):
print("Side:", side)
print("Points:", (x,y), (x+side, y), (x,y + side), (x+side, y+side))
else:
print("No such square")
n = 6
points=[(2, 2), (5, 5), (4, 5), (5, 4), (2, 5), (5, 2)]
get_square_points(points, n)

## Input

6, [(2, 2), (5, 5), (4, 5), (5, 4), (2, 5), (5, 2)]

## Output

Side: 3 Points: (2, 2) (5, 2) (2, 5) (5, 5)