Choosing an Item Uniformly from a List

Selecting a uniform position gives equal probability to every position. Values repeated at several positions get greater total probability.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace an input with duplicates
  2. Check empty input
  3. Specify whether positions or distinct values are equally likely
  4. Test the sampling range and its empty case

Trace an input with duplicates

From [A, A, B], a uniform position selects A with probability two thirds. If the intended choices are labels, build the distinct labels first so A and B each have probability one half. Set and sequence models explain the difference.

Check empty input

An empty list supplies no valid draw. The caller must handle that outcome under its function contract, even when ordinary runs always have one or more choices.[1]

Specify whether positions or distinct values are equally likely

Selecting a uniformly random position from [red, red, blue] returns red with probability two thirds. Choosing uniformly among distinct values gives red one half. The discrepancy comes from the two red positions counted separately in the first model. See sets and sequences.

Position 0 → red
Position 1 → red
Position 2 → blue
Color probabilities: red 2/3, blue 1/3

Test the sampling range and its empty case

Draw an index from zero through length minus one. An inclusive upper bound equal to length can point outside the list. An empty list offers no possible sample and needs an explicit outcome. Validate repeated values against the intended population.

References

  1. Eric Lehman, F. Thomson Leighton and Albert R. Meyer, Mathematics for Computer Science ↩