## Code Generator for Discrete Distributions

This page generates standalone programming code that samples from a discrete distribution, or instructions to choose a random number by flipping a real coin or rolling a real die. That is, the code or instructions are designed to choose an integer in [0, n) at random where each of the n integers has a separate probability of occurring. The idea for a code generator like this came from Leydold et al. (2001). The generator supports generating JavaScript code, Ruby code, or coin-flipping instructions.

The code generator is powered by the recently presented Fast Loaded Dice Roller (Saad et al. 2020) and by the Fast Dice Roller (Lumbroso 2013). The code generator is also powered by JavaScript, at least the kind supported by modern Web browsers. Accordingly, the generator requires JavaScript (active scripting) to be enabled in the browser settings.

This is an open-source generator written by Peter Occil. Any copyright to this page is released to the Public Domain. In case this is not possible, this page is also licensed under Creative Commons Zero. If you have comments or issues on this generator, send them to the GitHub issues page.

### About the Coin-Flipping and Die-Rolling Instructions

This generator supports generating instructions that choose a non-uniform random number by flipping a real coin or rolling a real six-sided die.

- The coin-flipping instructions were generated by running the Fast Loaded Dice Roller on fixed sequences of coin flip results (such as H/T/T/H/H). For dice specifications, the coin-flipping instructions were generated similarly to the die-rolling instructions instead, because it's considerably faster than checking all sequences with the Fast Loaded Dice Roller.
- The die-rolling instructions implement a variant of the "greedy simulation" process described in B. Kloeckner, "Simulating a dice with a dice", 2008, except it supports any non-uniform discrete distribution (within reason), that is, the output die can be a loaded die, not just a fair one. The die-rolling instructions allow a non-uniform random number to be chosen by rolling a real (fair) six-sided die.

### References

Saad, F.A., Freer C.E., et al. "The Fast Loaded Dice Roller: A Near-Optimal Exact Sampler for Discrete Probability Distributions", in _AISTATS 2020_ 108.

Leydold, et al., "An Automatic Code Generator for Nonuniform Random Variate Generation", 2001.

Lumbroso, J., "Optimal Discrete Uniform Generation from Coin Flips, and Applications", arXiv:1304.1916 [cs.DS]