WeightedRandom.Backend.Linear (weighted_random v1.0.1)

Copy Markdown View Source

This is a very naive approach. Quick and dirty to implement, but definitely not as fast as most other backends, especially at scale. One advantage it has is a very fast and simple preprocessing phase. So if you only need to run it once or twice at a time, this can actually beat the Walker Alias Method.

How it works

  1. During preprocessing, build a list of running totals of the weights, e.g. [1.0, 2.5, 3.0].
  2. During take, pick a random point between 0 and the total weight.
  3. Walk the list and return the index of the first running total greater than that point. Higher weights cover a wider span, so they are picked more often.