Loaded Die

Loaded Die is a Ruby library that makes it easy to randomly choose from a set
of options where some options are more likely than others.


Usage

This is the basic pattern: First, you load the library. Then you create an
instance of LoadedDie::Sampler and send the sample message to it as many
times as you like.

Let's say you want to choose randomly from three strings: "A", "B", and "C".
You want "A" and "B" to be equally likely, and "C" to be twice as likely as one
of them. That means "A" should be 25% likely, B should be 25% likely, and C
should be 50% likely.

You can create your sampler like this:

require "loaded_die"
sampler = LoadedDie::Sampler.new({ "A" => 0.25, "B" => 0.25, "C" => 0.5 })

And then sample from it like this:

sampler.sample

But you don't need to be fussy about how you represent probabilities. That is,
you don't need to represent them as numbers between zero and one such that they
sum to one. Their relative values are what matter. Furthermore, they don't need
to be floats, just objects that convert to floats. So you could also create
your sampler like this:

sampler = LoadedDie::Sampler.new({ "A" => 1, "B" => 1, "C" => 2 })

You can specify the random number generator that sample uses. To do this,
supply as the argument a hash with your random number generator under the
:random key. (This is based on the behavior of Ruby's Array#sample.) Your
random number generator will be sent a rand message with one argument, the sum
of the weights you specified when creating the sampler. The returned object
must be a float greater than or equal to zero and less than the sum of the
weights.

rng = Object.new
def rng.rand(n)
0.0
end
sampler.sample({ :random => rng })