# Calculate largest square in rectangle with a given vertex

There are two points `(x1, y1)` and `(x2, y2)`, each of which can be any real integer pair. These define a rectangle `R` with vertices `{(x1, y1), (x2, y2), (x1, y2), (x2, y1)}`. The rectangle exists in a coordinate system where `(0, 0)` is the top left corner of the screen, positive y is down and positive x is right. I need to calculate the largest possible square `S` bound by `R` that has for one of it's corners the point `(x1, y1)`.

My algorithm is:

1. Given the vertices (x1, y1) and (x2, y2)

2. Calculate the width and height of the rectangle and store the smallest as size.

3. If x2 > x1 and y2 < y1, return the square of size with upper left corner (x1 + size, y1 - size)

4. If x2 < x1 and y2 < y1, return the square of size with upper left corner (x1 - size, y1 - size)

5. If x2 < x1 and y2 > y1, return the square of size with upper left corner (x1 - size, y1)

6. If x2 > x1 and y2 > y1, return the square of size with upper left corner (x1 + size, y1)

However, it seems like there must be a more efficient way. Any ideas?

EDIT

Context: I need to draw a square by clicking and dragging the mouse. The initial mouse down is one corner. The square is defined by the minimum between the height and width of the rectangle formed by dragging the mouse. The square needs to expand out in all four possible directions, but the data structure only allows me to hold the square as an upper left point and a size.