Given an arraylist of rectangles, my task is to find the smallest rectangle enclosing all the other rectangles.
import java.awt.Rectangle;
import java.util.ArrayList;
public class Homework {
public static void main(String[] args) {
ArrayList<Rectangle> test = new ArrayList<Rectangle>();
test.add(new Rectangle(10, 20, 30, 40));
test.add(new Rectangle(20, 10, 30, 40));
test.add(new Rectangle(10, 20, 40, 50));
test.add(new Rectangle(20, 10, 50, 30));
Rectangle enc = enclosing(test);
System.out.println(enc);
System.out.println("Expected: java.awt.Rectangle[x=10,y=10,width=60,height=60]");
}
public static Rectangle enclosing(ArrayList<Rectangle> rects) {
// Your work here
}
}
What I have so far:
public static Rectangle enclosing(ArrayList<Rectangle> rects) {
double topLeftX = Integer.MAX_VALUE;
double topLeftY = Integer.MAX_VALUE;
double bottomRightX = Integer.MIN_VALUE;
double bottomRightY = Integer.MIN_VALUE;
for (Rectangle r : rects) {
if (r.getX() < topLeftX)
topLeftX = r.getX();
if (r.getY() < topLeftY)
topLeftY = r.getY();
if ((r.getX() + r.getWidth()) > bottomRightX)
bottomRightX = (r.getX() + r.getWidth());
if ((r.getY() + r.getHeight()) > bottomRightY)
bottomRightY = (r.getY() + r.getHeight());
}
Rectangle.Double enc = new Rectangle.Double(topLeftX, topLeftY, bottomRightX - topLeftX, bottomRightY - topLeftY);
return enc;
}
I get an “incompatible types” error for my return line. I’m not sure what goes there to make the output match the tester block at the top.
Thanks in advance! 🙂
Change
to