-2

I have 2 values and want to create a rectangle from it.

enter image description here

So let's say:

1 = 1,1
2 = 10,8

So I want to calculate the upper left corner which would result in 1,8 and the lower right corner which would be 10,1. How can I achieve this with Java? Are there any libraries for this or is it even possible with the standard equipment?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user754730
  • 1,341
  • 5
  • 31
  • 62
  • That wouldn't be a square. Do you mean a rectangle with sides that are exactly vertical or horizontal (not crooked)? – nanofarad Nov 24 '14 at 11:31
  • Sorry of course I mean a rectangle and not a square... – user754730 Nov 24 '14 at 11:32
  • There shouldn't be any need for a library, beyond maybe a really simple `Point` class that contains an x coordinate and a y coordinate. – nanofarad Nov 24 '14 at 11:35
  • Your example values don't make any sense. If you have point 1 at x=1,y=1 and point 2 at x=10,y=8, you already have the upper left corner and lower right corner. – Boann Nov 24 '14 at 11:36
  • @hexafraction, I thought all rectangles have straight, not crooked lines. Or are we talking about hyperspace i.e. a galaxy far, far away? – CocoNess Nov 24 '14 at 11:36
  • @CocoNess I meant axis-aligned. – nanofarad Nov 24 '14 at 11:40

3 Answers3

2

All you need to do is take the min/max x/y of the existing points:

Point p1 = ...
Point p2 = ...

Point upperLeft  = new Point(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y));
Point lowerRight = new Point(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y));

Note: This assumes x increases as you go right and y increases as you go down. If you have y increasing as you go up, change to:

Point upperLeft  = new Point(Math.min(p1.x, p2.x), Math.max(p1.y, p2.y));
Point lowerRight = new Point(Math.max(p1.x, p2.x), Math.min(p1.y, p2.y));
Boann
  • 48,794
  • 16
  • 117
  • 146
1

Based on your diagram and example, you want a rectangle with vertical and horizontal sides. If you look at your current example, all you did was take x1 and y2 for one of the points, and x2/y1 for the other point.

So, given Points p1 and p2, you could do as follows:

Point p3 = new Point(p1.x, p2.y);
Point p4 = new Point(p2.x, p1.y);

Of course, if you do not have Point objects you can just use the numbers as variables accordingly.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
1

here is some code to start with:

public class Test {
    public static void main(String[] args) {
        int x1, x2, x3, x4, y1, y2, y3, y4;
        x1 = 1; y1 = 1;
        x3 = 10; y3 = 8;

        x4 = x1;y4 = y3;
        x2 = x3; y2 = y1;

        System.out.println("(x4,y4)=("+ x4 + "," + y4 + ")\t\t (x3,y3)=(" + x3 + "," + y3+")");
        System.out.println("(x1,y1)=("+ x1 + "," + y1 + ")\t\t (x2,y2)=(" + x2 + "," + y2+")");

    }
}

Result is:

(x4,y4)=(1,8)        (x3,y3)=(10,8)
(x1,y1)=(1,1)        (x2,y2)=(10,1)
Naruto Biju Mode
  • 2,011
  • 3
  • 15
  • 28