+ /* Decide whether this is the winning track.
+ *
+ * Suppose that we have n things, and thing i, for 0 <= i < n, has weight
+ * w_i. Let c_i = w_0 + ... + w_{i-1} be the cumulative weight of the
+ * things previous to thing i, and let W = c_n = w_0 + ... + w_{i-1} be the
+ * total weight. We can clearly choose a random thing with the correct
+ * weightings by picking a random number r in [0, W) and chooeing thing i
+ * where c_i <= r < c_i + w_i. But this involves having an enormous list
+ * and taking two passes over it (which has bad locality and is ugly).
+ *
+ * Here's another way. Initialize v = -1. Examine the things in order;
+ * for thing i, choose a random number r_i in [0, c_i + w_i). If r_i < w_i
+ * then set v <- i.
+ *
+ * Claim. For all 0 <= i < n, the above algorithm chooses thing i with
+ * probability w_i/W.
+ *
+ * Proof. Induction on n. The claim is clear for n = 1. Suppose it's
+ * true for n - 1. Let L be the event that we choose thing n - 1. Clearly
+ * Pr[L] = w_{n-1}/W. Condition on not-L: then the probabilty that we
+ * choose thing i, for 0 <= i < n - 1, is w_i/c_{n-1} (induction
+ * hypothesis); undoing the conditioning gives the desired result.
+ */
+ D(("consider %s", track));
+ if(weight) {
+ total_weight += weight;
+ if (pick_weight(total_weight) < weight)
+ winning = track;