Skip to content

Instantly share code, notes, and snippets.

@jhm-ciberman
Created July 2, 2020 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhm-ciberman/bd8f25e46d134c9a3a5e4f07b606782b to your computer and use it in GitHub Desktop.
Save jhm-ciberman/bd8f25e46d134c9a3a5e4f07b606782b to your computer and use it in GitHub Desktop.
Weighted Random C#
class Test
{
public void Example()
{
var wr = new WeightedRandom<string>();
wr.Add("Fire", 0.5f);
wr.Add("Water", 2f);
wr.Add("Snow", 1f);
var result = wr.Next();
}
}
using System.Collections.Generic;
// Author: Javier "Ciberman" Mora
// License: MIT
// Enjoy!
public class WeightedRandom<T>
{
private struct Value
{
public T value;
public float probability;
public Value(T value, float probability)
{
this.value = value;
this.probability = probability;
}
}
private System.Random _random;
private List<Value> _weightedValues;
private float _sumOfProbabilities = 0f;
public WeightedRandom(int seed) : this(new System.Random(seed)) { }
public WeightedRandom() : this(new System.Random()) { }
public WeightedRandom(System.Random random)
{
this._random = random;
this._weightedValues = new List<Value>();
}
public WeightedRandom<T> Clear()
{
this._weightedValues.Clear();
this._sumOfProbabilities = 0f;
return this;
}
public WeightedRandom<T> Add(T value, float probability)
{
if (probability <= 0f) return this;
this._weightedValues.Add(new Value(value, probability));
this._sumOfProbabilities += probability;
return this;
}
public float sumOfProbabilities => this._sumOfProbabilities;
public T Next()
{
double p = this._random.NextDouble() * this._sumOfProbabilities;
foreach (var v in this._weightedValues)
{
p -= v.probability;
if (p <= 0) return v.value;
}
return default(T);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment