4
TreeMap<Integer, Integer> weightedRectIndex = new TreeMap<>();7
Random rng = new Random();9
public Solution(int[][] rects) {12
for (int[] rect : rects) {13
// inserts cumulative weight key pointing to rectangle index14
weightedRectIndex.put(nPoints, index++);15
nPoints += width(rect) * height(rect);20
// generates random point within total weight21
int point = rng.nextInt(nPoints);22
// finds appropriate rectangle23
var entry = weightedRectIndex.floorEntry(point);24
// find point within the current rectangle25
int rectPoint = point - entry.getKey();26
int[] rect = rects[entry.getValue()];27
return new int[] {rect[0] + rectPoint % width(rect), rect[1] + rectPoint / width(rect)};30
private int width(int[] rect) {31
return rect[2] - rect[0] + 1;34
private int height(int[] rect) {35
return rect[3] - rect[1] + 1;