-
Notifications
You must be signed in to change notification settings - Fork 277
/
RandomPointInNonOverlappingRectangles.java
38 lines (31 loc) · 1.19 KB
/
RandomPointInNonOverlappingRectangles.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class RandomPointInNonOverlappingRectangles {
Random rand = null;
TreeMap<Integer, Integer> map = null;
int[][] rects ;
int area;
public Solution(int[][] rects) {
rand = new Random();
map = new TreeMap<>();
this.rects = rects;
for(int i=0;i<rects.length;i++){
// Calculate the current Area
int currArea = (rects[i][2] - rects[i][0] +1) * (rects[i][3] - rects[i][1] +1);
area += currArea;
map.put(area, i); // cummulative sum vs id in rect
}
}
public int[] pick() {
int randInt = rand.nextInt(area); // Pick a random index
int index = map.higherKey(randInt); // find its higher Key in map
int[] rectChoosen = rects[map.get(index)]; // select a rectangle
// Choose the points in that rectangle
int x = rectChoosen[0] + (index - randInt -1) % (rectChoosen[2]- rectChoosen[0] +1);
int y = rectChoosen[1] + (index - randInt -1) / (rectChoosen[2]- rectChoosen[0] +1);
return new int[]{x, y};
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(rects);
* int[] param_1 = obj.pick();
*/