Created
October 10, 2023 14:34
-
-
Save SKumarSpace/4ec409c97dc6fb6ccb7c7c38b9de0dd5 to your computer and use it in GitHub Desktop.
Weighted Random Picker C#
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
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