Skip to content

Instantly share code, notes, and snippets.

@SKumarSpace
Created October 10, 2023 14:34
Show Gist options
  • Save SKumarSpace/4ec409c97dc6fb6ccb7c7c38b9de0dd5 to your computer and use it in GitHub Desktop.
Save SKumarSpace/4ec409c97dc6fb6ccb7c7c38b9de0dd5 to your computer and use it in GitHub Desktop.
Weighted Random Picker C#
for (int i = 0; i < 100; i++) {
var x = RandomPicker<string>.GetRandomChoice("A", 70, "B", 30);
Console.WriteLine(x);
}
public class RandomPicker<T> {
private static Random _random = new Random();
public static T GetRandomChoice(T valueA, int weightA, T valueB, int weightB) {
int totalWeight = weightA + weightB;
int randomNumber = _random.Next(1, totalWeight + 1);
if (randomNumber <= weightA) {
return valueA;
} else {
return valueB;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment