检查海龟是否在其他海龟的半径内

时间:2021-07-31 13:24:39

标签: java

我正在尝试编写一个方法来检查海龟是否在任何其他海龟的半径内。我通过使用两个循环遍历整个数组的 for 循环来完成此操作。在我向数组中添加很多海龟后,这似乎变慢了。有没有办法让它更有效率?

public void inRadius() {
        for (int i = 0; i < turtles.size(); i++) {
            for (int k = i + 1; k < turtles.size(); k++) {
               CartesianCoordinate position = new CartesianCoordinate(turtles.get(i).getXPosition(), turtles.get(i).getYPosition());
                turtles.get(k).checkRadius(position);
                if(turtles.get(k).checkRadius(position)) {
                System.out.println(turtles.get(k)+":"+turtles.get(k).checkRadius(position));
                
                    }
                
            }
        }
    }

这里是检查半径方法:

    public boolean checkRadius(CartesianCoordinate point) {
    
        double distance = Math.pow(point.getX()-getXPosition(),2) + Math.pow(point.getY()-getYPosition(),2);
        
        double rad =Math.pow(radius, 2);
        
        if (distance < rad) {
            inRadius=true;
        }
        if(distance> rad) {
            inRadius= false;
        }
        return inRadius;
        
    }

0 个答案:

没有答案