Random

About math random, not "random question".

Shuffle a Deck of Cards - Fisher–Yates Shuffle

A de facto algorithm to shuffle an array: Fisher–Yates Shuffle

A great visualization for the algorithm: https://bost.ocks.org/mike/shuffle/

In JavaScript

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

In Java

Modified based on Sam Allen's implementation: https://www.dotnetperls.com/shuffle-java

Reservoir Sampling

See also: reservoir sampling

Implementation: Select K Items from A Stream of N element

Weighted Random Distribution

https://www.electricmonk.nl/log/2009/12/23/weighted-random-distribution/

https://www.electricmonk.nl/docs/weighted_random_distribution/weighted_random_distribution.pdf

Discusses different ways of performing weighted random selection and compare their pros and cons such as time and space complexity.

Different approaches

Expanding

One of the easiest solutions is to simply expand our array/list so that each entry in it appears as many times as its weight.

In-place (Unsorted)

In-place (sorted)

Pre-calculated

Pre-calculate accumulated sums of the weights for each element, and then use binary search to find where in the range that the random number belongs to, thus returning the corresponding element.

See Random Pick with Weight from LeetCode.

Conclusion

If you need

speedy selections

  • Use expanded if the number of items in your set is low, and your weights are not very high.

  • Use pre-calculated if your set has lots of numbers and/or your weights are high.

If you need

speedy updates

  • Use in-place (unsorted) for the fastest updates.

  • Use in-place (sorted) for somewhat slower updates and somewhat faster selections.

If you need

low memory usage

  • Don’t use expanded.

If you need

simplicity

  • Use expanded or in-place (unsorted).

Last updated

Was this helpful?