Suppose that he is given a set of rectangles with different areas, and some rectangles may overlap. The task is to create a uniform random point among the areas of the rectangles.
A rectangle is defined as a pair of two points:
- (x1, y1) - lower left corner;
- (x2, y2) is the upper right corner.
My strategy for evenly distributing a random point among non-overlapping rectangles is to - 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 create an arbitrary point inside the rectangle:
- x1 + (1 / (x2-x1)) * rand (0, (x2-x1-1)),
- y1 + (1 / (y2-y1)) * rand (0, (y2-y1-1)).
But what if some of the rectangles may overlap?
source share