Skip to content

Instantly share code, notes, and snippets.

@DataGreed
Created January 31, 2019 02:25
Show Gist options
  • Save DataGreed/89a309b41af1d61684c037c1f28ed3be to your computer and use it in GitHub Desktop.
Save DataGreed/89a309b41af1d61684c037c1f28ed3be to your computer and use it in GitHub Desktop.
Weighted random choice - C# implementation
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