I thought, thought and finally came up with and debugged the algorithm. I checked the distance on the diamond principle
range = 3
....o....
...ooo...
..ooooo..
.oooXooo.
..ooooo..
...ooo...
....o....
- Create a one-dimensional
boolean
array. - We hammer in an array with
true
values (If true
, then the place is free) - Create a random coordinate within the field (For coordinates, I used my
Coordinate
class. In it, I defined only two fields. X and Y) - Check if the coordinate is available. (I used the
GetAddress
function)- If available (
true
), we generate coordinates around this point (I used the GetDiamondAreaCoordinates
function GetDiamondAreaCoordinates
, but any other of yours is possible. For example, a square area or a round one) and check with an iterator whether points are valid. - If not available, return to step 3.
- If each point of the area is not outside the field, in the
boolean
array through the GetAddress
function we GetAddress
false.- If outside, then continue the cycle.
public Coordinate[] GetDiamondAreaCoordinates(Coordinate coordinate, int range) { ArrayList<Coordinate> coordinates = new ArrayList<>(); int offsetHeight = 0, offsetWidth = range; int currentX = coordinate.getLeft(); int currentY = coordinate.getTop(); int localIterator = 0; for (int i = currentX-range; i < currentX+range+1; i++) { for (int j = currentY-offsetHeight; j < currentY+offsetHeight+1; j++) { coordinates.add(new Coordinate(i, j)); } offsetWidth --; offsetHeight += (currentX-offsetWidth <= currentX)? 1 : -1; } Coordinate[] resultCoords = coordinates.toArray(new Coordinate[coordinates.size()]); return resultCoords; }
private int getAddress(int top, int left) { int index = top*width+left; if (index >= 0 && index < width*height) return index; return -1; }