gpt4 book ai didi

Java 最小的矩形将其他矩形包围在 ArrayList 中

转载 作者:行者123 更新时间:2023-11-30 04:57:18 24 4
gpt4 key购买 nike

给定一个矩形数组列表,我的任务是找到包围所有其他矩形的最小矩形。

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
}
}

到目前为止我所拥有的:

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;
}

我的返回行收到“不兼容类型”错误。我不确定如何使输出与顶部的测试器 block 匹配。

提前致谢! :)

最佳答案

改变

Rectangle.Double enc = new Rectangle.Double(topLeftX, topLeftY, bottomRightX - topLeftX, bottomRightY - topLeftY);

Rectangle enc = new Rectangle((int) topLeftX, (int) topLeftY, (int) (bottomRightX - topLeftX), (int) (bottomRightY - topLeftY));

关于Java 最小的矩形将其他矩形包围在 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8117261/

24 4 0