# Untitled

By: a guest on May 15th, 2012  |  syntax: None  |  size: 1.49 KB  |  hits: 22  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1.     import java.util.*;
2. import java.awt.Rectangle;
3. public class Homework13A
4. {
5.    public static void main(String[] args)
6.    {
7.       ArrayList<Rectangle> test = new ArrayList<Rectangle>();
8.       test.add(new Rectangle(10, 20, 30, 40));
9.       test.add(new Rectangle(20, 10, 30, 40));
10.       test.add(new Rectangle(10, 20, 40, 50));
11.       test.add(new Rectangle(20, 10, 50, 30));
12.       Rectangle enc = enclosing(test);
13.       System.out.println(enc);
14.       System.out.println("Expected: Rectangle[x=10,y=10,width=61,height=61]");
15.    }
16.
17.    /**
18.       Computes the smallest rectangle enclosing all rectangles in
19.       an array list.
20.       @param rects an array list of rectangles of size >= 1
21.       @return the smallest rectangle enclosing all rectangles in rect
22.    */
23.    public static Rectangle enclosing(ArrayList<Rectangle> rects)
24.    {
25.     double leftX = Integer.MAX_VALUE;
26.     double leftY = Integer.MAX_VALUE;
27.     double rightX = Integer.MIN_VALUE;
28.     double rightY = Integer.MIN_VALUE;
29.
30.         for (Rectangle r : rects) {
31.         if (r.getX() < leftX)
32.             leftX = r.getX();
33.         if (r.getY() < leftY)
34.             leftY = r.getY();
35.
36.         if ((r.getX() + r.getWidth()) > rightX)
37.             rightX = (r.getX() + r.getWidth());
38.
39.         if ((r.getY() + r.getHeight()) > rightY)
40.             rightY = (r.getY() + r.getHeight());
41.     }
42.     Rectangle enc = new Rectangle((int) leftX, (int) leftY, (int) (rightX - leftX), (int) (rightY - leftY));
43.
44.     return enc;
45.    }
46. }