Assume it's given a set of rectangles with different areas and some rectangles could overlap. Objective is generating of a uniform random point among rectangles' areas.
Rectangle is defined as a pair of two points:
My strategy for uniform distribution of a random point among not overlapped rectangles is that,- randomly select a rectangle based on areas (existing solution):
for(int i = 0; i < rectangles.length; i++) {
int area = (rectangles[i].x2 - rectangles[i].x1) *
(rectangles[i].y1 - rectangles[i].y2);
if(rand.nextInt(total + area) >= total) {
selected = i;
break;
}
total += area;
}
Then generate an arbitrary point within a rectangle:
But how to be if some of rectangles could overlap?
Here is a simple and very fast solution if the first preprocessing step is fast enough (assumes rectangles are integer coordinates less than say.. 1000):
squares = set()
for rect in rects:
for oneByOneSquare in rect:
squares.add(oneByOneSquare)
squares = list(squares)
while True:
randomSquare = random.choice(squares)
randomPoint = randomPointInsideSquare(randomSquare)
The idea is to partition the rectangles into squares. Then randomly select squares and the randomly generate a point within that square.
An industrial-grade solution would be
This approach is applicable to any input of potentially overlapping polygons, if you replace the second step with any kind of triangulation (like trapezoidal decomposition followed by triangulation) and then select the point from the final set of triangles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With