Random Point in Non-overlapping Rectangles
Over 50% downvotes
You can create a class to manage the given rectangles and implement a function to pick a random integer point inside one of the rectangles. Here’s Python code:
|
|
Explanation:
- We’re using a binary search to efficiently locate the target rectangle. The
_binary_search
method locates the rectangle that the random value falls within. - In the
pick
method, we select a random value and find the corresponding rectangle. Then we return a random point within that rectangle’s bounds. - The weights are used to ensure that each point in the overall space is equally likely to be chosen. We store the cumulative weights, where the weight of a rectangle is proportional to its area.