Created
January 31, 2019 02:25
-
-
Save DataGreed/89a309b41af1d61684c037c1f28ed3be to your computer and use it in GitHub Desktop.
Weighted random choice - C# implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
class WeightedRandomBag<T> { | |
private struct Entry { | |
public double accumulatedWeight; | |
public T item; | |
} | |
private List<Entry> entries = new List<Entry>(); | |
private double accumulatedWeight; | |
private Random rand = new Random(); | |
public void AddEntry(T item, double weight) { | |
accumulatedWeight += weight; | |
entries.Add(new Entry { item = item, accumulatedWeight = accumulatedWeight }); | |
} | |
public T GetRandom() { | |
double r = rand.NextDouble() * accumulatedWeight; | |
foreach (Entry entry in entries) { | |
if (entry.accumulatedWeight >= r) { | |
return entry.item; | |
} | |
} | |
return default(T); //should only happen when there are no entries | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment