# Random Point in Non-overlapping Rectangles in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of non-overlapping axis-aligned rectangles rects, we have to write a function pick which randomly and uniformly picks an integer number, point in the space covered by the rectangles. So we have to keep in mind some points −

• An integer point is a point that has integer coordinates.
• A point on the perimeter of a rectangle is included in the space covered by the rectangles.
• The ith rectangle = rects[i] denotes [x1,y1,x2,y2], where [x1, y1] are the integer coordinates of the bottom-left corner, and [x2, y2] are the integer coordinates of the top-right corner.
• The length and the width of each rectangle does not exceed 2000.
• 1 <= rects.length <= 100
• pick return a point as an array of integer coordinates [p_x, p_y]

If the input is like [1,1,5,5], and we call pick() three times, then the output will be [4,1], [4,1], [3,3]

To solve this, we will follow these steps −

• Make two arrays area and rect
• In the initializer do the following −
• rect := rects, sum := 0
• for i in range 0 to size of rects – 1
• (x1, y1) := (rects[i, 0], rects[i, 1])
• (x2, y2) := (rects[i, 2], rects[i, 3])
• temp := |x2 – x1 + 1| * |y2 – y1 + 1|
• sum := sum + temp, and insert sum into area
• In the pick method, do the following −
• randArea := random number mod sum + 1
• for i in range 0 to size of area – 1
• if randArea <= area[i], then come out from the loop
• dist_x := random number mod |rect[i,0] – rect[i,2] + 1|
• dist_y := random number mod |rect[i,1] – rect[i,3] + 1|
• return a pair (dist_x + rect[i, 0], dist_y + rect[i, 1])

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector <int> area;
vector < vector <int> > rect;
int sum;
Solution(vector<vector<int> >& rects) {
rect = rects;
sum = 0;
for(int i =0 ; i < rects.size(); i++){
int x1 = rects[i][0];
int y1 = rects[i][1];
int x2 = rects[i][2];
int y2 = rects[i][3];
int temp = (abs(x2 - x1) + 1) * (abs(y2 - y1) + 1);
sum += temp;
area.push_back(sum);
}
}
vector<int> pick() {
int randArea = rand() % sum + 1;
int i;
for(i = 0; i < area.size(); i++){
if(randArea <= area[i]) break;
}
int dist_x = rand() % (abs(rect[i][0] - rect[i][2] ) + 1);
int dist_y = rand() % (abs(rect[i][1] - rect[i][3] ) + 1);
return {dist_x + rect[i][0], dist_y + rect[i][1]};
}
};
main(){
vector<vector<int> > v = {{1, 1, 5, 5}};
Solution ob(v);
print_vector(ob.pick());
print_vector(ob.pick());
print_vector(ob.pick());
}

## Input

["Solution", "pick", "pick", "pick"]
[[[[1, 1, 5, 5]]], [], [], []]

## Output

[2, 3, ]
[4, 1, ]
[3, 5, ]
Published on 02-May-2020 13:08:13