Random Pick with Weight
Pick an index at random so that heavier indexes come up more often, in exact proportion to their weights.
Given an array wwpickIndex()w[i]
Example 1
Output: pickIndex() returns 0 about 25% of the time and 1 about 75% of the time.
Example 2
Output: pickIndex() returns 0 about 20% of the time, 1 about 50% and 2 about 30%.
The Idea
Think of a raffle where some people bought more tickets than others. In Example 1, index 0 holds one ticket and index 1 holds three. One ticket is drawn out of the four, so index 1 wins three times out of four, 75%, and index 0 wins the other 25%.
So each weight can be read as a number of tickets. Example 2 has 2 + 5 + 3 = 10 tickets. Give them numbers in a row: index 0 gets tickets 1 and 2, index 1 gets tickets 3 to 7, and index 2 gets tickets 8 to 10. Drawing one number from 1 to 10, each equally likely, picks index 1 five times in ten.
Drawing a number is easy. The real question is the other half: once ticket 6 comes out, whose ticket is it? The picture below lays the tickets of Example 2 out in a row and follows ticket 6.
Under the row, each index's last ticket is marked with a running total of the weights so far: prefix 2, prefix 7 and prefix 10. A running total like this, the sum of the first few weights, is called a prefix sum. The arrow labelled "drawn ticket: target = 6" points at ticket 6, and target
Which index owns ticket 6? Walk along the totals. Index 0's tickets end at 2, which is before 6. Index 1's tickets end at 7, which is 6 or more, so ticket 6 is one of them. The owner is the first index whose prefix sum is at least the ticket number.
The prefix sums only grow, because every weight is positive. That means the search does not have to walk them one by one. The lines headed "Binary search on prefix = [2, 7, 10]" start in the middle: prefix 7 is at least 6, so the owner is index 1 or an index before it. Then prefix 2 is less than 6, so index 0 is ruled out, and index 1 is left.
Each look at a middle total rules out half of the indexes still in the running. Searching the growing totals by halving them like this is called binary search. With three weights it took two looks; with a million weights it takes about 20.
Solution Approach
Four things need settling: what the constructor stores, how pickIndex
Storing the running totals
What should the constructor keep? The simplest idea is a list with one entry per ticket, holding its owner, so a draw is a single lookup. But that list is as long as the sum of the weights, and two weights of a billion would need two billion entries. The prefix sums say the same thing in one entry per weight, so the constructor stores those in an array named prefix
Drawing a ticket
How do we draw a ticket number from 1 to the total, each equally likely? Java's Random.nextLong(total)total - 1totaltarget
Finding the ticket's owner
Which index owns targetlohimid
If prefix[mid]targetmidlomid + 1midhimid
The middle is computed as (lo + hi) >>> 1/ 2intlohiint/ 2
Totals larger than an int
Can the total itself be too big? A Java intInteger.MAX_VALUEintnextInt(-2)prefixlongnextLonglong
Java Solution
The class has four parts, one for each decision:
: the running totals of the weights, asprefix values. Entrylong is the last ticket number that belongs to index i.prefix[i]- The constructor: one pass over
that adds each weight tow and stores it insum . A second constructor takes aprefix from outside, so a test can pass one with a fixed seed.Random : drawspickIndex from 1 to the total withtarget .random.nextLong(total) + 1- The
loop inwhile : the binary search for the first index whose prefix sum is at leastpickIndex .target
Random picks would print different numbers on every run, so mainRandomcountPickspickIndex
The mainInteger.MAX_VALUE
import java.util.Arrays;
import java.util.Random;
public class RandomPickWithWeight {
private final long[] prefix; // prefix[i] = w[0] + ... + w[i]
private final Random random;
public RandomPickWithWeight(int[] w) {
this(w, new Random());
}
RandomPickWithWeight(int[] w, Random random) { // a seeded Random gives repeatable picks
this.random = random;
prefix = new long[w.length];
long sum = 0;
for (int i = 0; i < w.length; i++) {
sum += w[i];
prefix[i] = sum;
}
}
public int pickIndex() {
long total = prefix[prefix.length - 1];
long target = random.nextLong(total) + 1; // a ticket from 1 to total
int lo = 0;
int hi = prefix.length - 1;
while (lo < hi) { // first index with prefix >= target
int mid = (lo + hi) >>> 1;
if (prefix[mid] < target) {
lo = mid + 1; // index mid's tickets end too early
} else {
hi = mid; // index mid's tickets reach target
}
}
return lo;
}
static void countPicks(int[] w, int picks) {
RandomPickWithWeight picker = new RandomPickWithWeight(w, new Random(42));
int[] counts = new int[w.length];
for (int k = 0; k < picks; k++) {
counts[picker.pickIndex()]++;
}
System.out.println("w = " + Arrays.toString(w) + ", prefix = "
+ Arrays.toString(picker.prefix) + ", counts = " + Arrays.toString(counts));
}
public static void main(String[] args) {
countPicks(new int[] {1, 3}, 100000);
countPicks(new int[] {2, 5, 3}, 100000);
countPicks(new int[] {7}, 1000);
countPicks(new int[] {Integer.MAX_VALUE, Integer.MAX_VALUE}, 100000);
}
}
Running it prints:
w = [1, 3], prefix = [1, 4], counts = [24938, 75062]
w = [2, 5, 3], prefix = [2, 7, 10], counts = [20033, 49755, 30212]
w = [7], prefix = [7], counts = [1000]
w = [2147483647, 2147483647], prefix = [2147483647, 4294967294], counts = [50169, 49831]
For [1, 3][2, 5, 3]
With the single weight 7, all 1,000 picks returned index 0, since the search loop never runs when lohi
The + 1target[1, 3]
Complexity
The constructor does its work once, and every call to pickIndex
- Time to build: O(n), because the constructor's loop adds each of the n weights to the running sum once.
- Time per pick: O(log n), because each pass of the search loop halves the range from
tolo , so three weights take two passes and a million take about 20.hi - Space: O(n), because
keeps one total per weight, however large the weights are, andprefix uses only a few local variables.pickIndex
The search for the first total that is at least target