How to optimize this code to make only the outline of an array of circles?

I have an array of a Unit object, and a single object has a center cx, cy and radius cr. I want only the outlines of the circles to be displayed (think of a diagram in Vienna without overlapping bits). I managed to do this, but this makes it very slow, as it is a nested loop. Here is the code:

(all this in a method that cycles through all units)

ArrayList<Integer> validangles = new ArrayList<Integer>(); public void getValidAngles(ArrayList<Unit> units) { //get all the angles that aren't overlapping ArrayList<Integer> invalidAngles = new ArrayList<Integer>(); for (int i = 0; i < units.size(); i++) { //cycle through all other units Unit c2 = units.get(i); if (this != c2) { //make sure it is not the same unit for (int ia = 0; ia < 360; ia += 10) { //cycle through the angles double ca = Math.toRadians(ia); Point p = new Point( //point on the circle (int) Math.round((c2.getCx() + (cr * Math.cos(ca)))), (int) Math.round((c2.getCy() + (cr * Math.sin(ca))))); if (overlapping(p)) { invalidAngles.add(ia-180); //this angle should not be shown } } } } validangles.clear(); for (int i = 0; i < 360; i += 10) { if (!invalidAngles.contains(i-180)) { validangles.add(i-180); } } } public void drawValidAngles(Graphics g2) { for(int i : validangles) { int x = (int)Math.round(cx+cr*Math.cos(Math.toRadians(i))); int y = (int)Math.round(cy+cr*Math.sin(Math.toRadians(i))); g2.drawLine(x, y, x, y); } } 

The problem is that if I have a couple of hundred units that will be distributed, this will slow down the program per ton due to the fact that the nested blocks are in another trap of units.

+5
source share
1 answer

You can use the Area class to combine ellipses (each ellipse represents a Unit shape). For instance.

  Shape s=new Ellipse2D.Float(10,10,200,100); Area a=new Area(new Ellipse2D.Float(150,20,100,200)); a.add(new Area(s)); 

Then you can use the sum as a path. See a working example here.

0
source

All Articles