3
* @param {number[][]} rects5
var Solution = function (rects) {9
// we put in the map the number of points that belong to each rect10
for (let i in rects) {11
const rect = rects[i];12
// the number of points can be picked in this rectangle13
this.sum += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1);14
this.map[this.sum] = i;16
this.keys = Object.keys(this.map);22
Solution.prototype.pick = function () {23
// random point pick between [1, this.sum]24
const randomPointPick = Math.floor(Math.random() * this.sum) + 1;26
// we look for the randomPointPick in the keys of the map28
// the keys exists in map29
if (this.map[randomPointPick]) pointInMap = randomPointPick;30
// the key is the first in the map (we do this check before doing binary search because its out of boundery)31
else if (randomPointPick < this.keys[0]) pointInMap = this.keys[0];32
let high = this.keys.length;34
// binary search to find the closest key that bigger than randomPointPick35
while (low <= high && !pointInMap) {36
const mid = Math.floor(low + (high - low) / 2);38
randomPointPick > this.keys[mid - 1] &&39
randomPointPick < this.keys[mid]41
pointInMap = this.keys[mid];43
} else if (randomPointPick > this.keys[mid]) {50
// we have the point, now we can get which rect belong to that point51
const pointInRects = this.map[pointInMap];52
const chosen = this.rects[pointInRects];53
const rightX = chosen[2];54
const leftX = chosen[0];55
const topY = chosen[3];56
const bottomY = chosen[1];57
const pickX = Math.floor(Math.random() * (rightX - leftX + 1)) + leftX;58
const pickY = Math.floor(Math.random() * (topY - bottomY + 1)) + bottomY;59
return [pickX, pickY];63
* Your Solution object will be instantiated and called as such:64
* var obj = new Solution(rects)65
* var param_1 = obj.pick()