Java生成圆而没有现有圆的交集

时间:2015-04-16 14:58:01

标签: java algorithm

我有结构:

public class Circle
{
    private int x;
    private int y;
    private int radius;

    private static final int color = Color.WHITE;

    public Circle(int x, int y, int radius)
    {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public int getRadius()
    {
        return radius;
    }

    public int getY()
    {
        return y;
    }

    public int getX()
    {
        return x;
    }

    public int getColor()
    {
        return color;
    }
}

并将其存储在Stack<Circle>

我想生成一个新的圈子,其中{strong}没有交叉其他圈子Stack

按照this回答我接下来做了:

public Circle generateNew(Stack<Circle> circles)
{
    Circle circle = null;
    while (circle == null)
    {
        int x0 = new Random().nextInt(mMaxWidth);
        int y0 = new Random().nextInt(mMaxHeight);
        int R0 = new Random().nextInt(5) * 25;
        boolean isIntersect = !circles.isEmpty();
        for (Circle c : circles)
        {
            int x1 = c.getX();
            int y1 = c.getY();
            int R1 = c.getRadius();
            int d = (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
            if (((R0 - R1) * (R0 - R1) <= d && d <= (R0 + R1) * (R0 + R1)))
            {
                isIntersect = true;
            }
        }
        if (!isIntersect)
        {
            circle = new Circle(x0, y0, R0);
        }
    }
    return circle;
}

但它没有用。我做错了什么?

尝试生成第二个圆圈后记录:

x0 = 496
y0 = 487
R0 = 100

x1 = 1121
y1 = 188
R1 = 100

2 个答案:

答案 0 :(得分:6)

保持简单

    boolean isIntersect = false;
    for (Circle c : circles)
    {
        int x1 = c.getX();
        int y1 = c.getY();
        int R1 = c.getRadius();
        int distanceSq = (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
        if (distanceSq <= (R0 + R1) * (R0 + R1))
        {
            isIntersect = true;
            break;
        }

答案 1 :(得分:1)

使用@Joop Eggen代码进行更多重构:

public Circle generateNew(Stack<Circle> circles)
{
    while (true)
    {
        int x0 = new Random().nextInt(mMaxWidth);
        int y0 = new Random().nextInt(mMaxHeight);
        int R0 = new Random().nextInt(5) * 25;
        boolean isIntersect = false;
        for (Circle c : circles)
        {
            int x1 = c.getX();
            int y1 = c.getY();
            int R1 = c.getRadius();
            int distanceSq = (x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1);
            if (distanceSq <= (R0 + R1) * (R0 + R1))
            {
                isIntersect = true;
                break;
            }
        }
        if (!isIntersect)
        {
            return new Circle(x0, y0, R0); 
        } 
    }
}