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 w of positive weights, write a class whose constructor takes w and whose method pickIndex() returns a random index of the array. Index i must come back with probability w[i] divided by the sum of all the weights, so an index with twice the weight comes back twice as often.

Example 1
Input: w = [1, 3]
Output: pickIndex() returns 0 about 25% of the time and 1 about 75% of the time.
Example 2
Input: w = [2, 5, 3]
Output: pickIndex() returns 0 about 20% of the time, 1 about 50% and 2 about 30%.
Solution

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.

The weights 2, 5 and 3 as 10 tickets in a row. Index 0 owns tickets 1 and 2, index 1 owns 3 to 7, index 2 owns 8 to 10. The running totals prefix 2, prefix 7 and prefix 10 mark where each index's tickets end. The drawn ticket, target = 6, belongs to index 1, and binary search finds it in two steps.

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 is the name the code gives the drawn number.

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 draws a ticket, how it finds the ticket's owner, and how to keep the totals right when the weights are large.

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) returns a whole number from 0 to total - 1. Adding 1 shifts it to 1 to total, the ticket numbers in the picture. The drawn number is called target in the code.

Finding the ticket's owner

Which index owns target? Checking the totals from left to right works, but it can take one step per weight on every draw. Binary search keeps two markers, lo and hi, around the indexes that could still be the owner. It looks at the total in the middle, mid.

If prefix[mid] is less than target, the tickets of index mid end too early, so lo moves to mid + 1. Otherwise mid could be the owner, so hi moves to mid, keeping it in range. When the markers meet, they sit on the owner.

The middle is computed as (lo + hi) >>> 1, which shifts the sum one bit to the right and so halves it. Unlike / 2, the shift still halves correctly when the sum has wrapped around to a negative int. With lo at 2,000,000,000 and hi at 2,100,000,000, the sum is too big for an int: / 2 gives -97,483,648, while the shift gives the true middle, 2,050,000,000.

Totals larger than an int

Can the total itself be too big? A Java int stops at 2,147,483,647, which is Integer.MAX_VALUE. Two weights of that size add up to 4,294,967,294 tickets. As an int, that sum wraps around to -2, and nextInt(-2) throws an exception. So prefix holds long values, and the draw uses nextLong, which accepts a long total.

Java Solution

The class has four parts, one for each decision:

  • prefix: the running totals of the weights, as long values. Entry prefix[i] is the last ticket number that belongs to index i.
  • The constructor: one pass over w that adds each weight to sum and stores it in prefix. A second constructor takes a Random from outside, so a test can pass one with a fixed seed.
  • pickIndex: draws target from 1 to the total with random.nextLong(total) + 1.
  • The while loop in pickIndex: the binary search for the first index whose prefix sum is at least target.

Random picks would print different numbers on every run, so main gives each picker a Random with the fixed seed 42, which repeats the same draws every time. A helper, countPicks, makes a picker, calls pickIndex many times and prints how often each index came back.

The main method counts 100,000 picks for each example and for two weights of Integer.MAX_VALUE, and 1,000 picks for an array with a single weight.

Java
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:

Output
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], index 0 came back 24,938 times out of 100,000, close to 25%, and index 1 came back 75,062 times. For [2, 5, 3], the counts 20,033, 49,755 and 30,212 sit near 20%, 50% and 30%. Random counts drift a little from the exact shares, and a different seed gives slightly different numbers.

With the single weight 7, all 1,000 picks returned index 0, since the search loop never runs when lo and hi both start at 0. The last line shows the second total as 4,294,967,294, the true sum, and the two equal weights split the picks about evenly.

The + 1 in the draw matters. Without it, target runs from 0 to 3 for [1, 3]. Both 0 and 1 are at most prefix 1, the end of index 0's tickets, so index 0 owns two of the four possible draws. A run of that version with the same seed counted 49,819 picks of index 0 and 50,181 of index 1, an even split instead of 25% and 75%.

Complexity

The constructor does its work once, and every call to pickIndex is one draw and one binary search over the n weights.

  • 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 lo to hi, so three weights take two passes and a million take about 20.
  • Space: O(n), because prefix keeps one total per weight, however large the weights are, and pickIndex uses only a few local variables.

The search for the first total that is at least target is the same pattern as in Binary Search Basics.