Skip to content

5.3.0

Choose a tag to compare

@BenMakesGames BenMakesGames released this 29 May 00:54
· 10 commits to main since this release

Added the following methods for picking elements from lists and sets with a weighting function, to control distribution:

  • T Random.WeightedNext(IReadOnlyList<T> list, Func<T, int> weightSelector)
  • T Random.WeightedNext(IReadOnlyList<T> list, Func<T, long> weightSelector)
  • T Random.WeightedNext(IReadOnlySet<T> list, Func<T, int> weightSelector)
  • T Random.WeightedNext(IReadOnlySet<T> list, Func<T, long> weightSelector)

Example:

var names = new string[] { "Abby", "Ben", "Carly" };
var name = Random.Shared.WeightedNext(names, x => x.Length);

In this example, each item is weighted based on its length, so longer names will be picked more often. Specifically, the total length of all names is 4 + 3 + 5 = 12. So, "Abby" has a 4/12 chance of being picked, "Ben" has a 3/12 chance, and "Carly" has a 5/12 chance.