0

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.

1

The maximum size of a square bounded by a rectangle will be the square of the shortest side of that rectangle. All you need to figure out is the height and width. Determine which is smaller. Set that value as the side of the square and then square that to get the area per standard.

Examples:

Example Rectangles

  • Let me add a bit more context as an edit. One sec... – AaronF Sep 15 '16 at 2:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.