Search code examples
pythonc#unity-game-engineprobability-distribution

does C# have something equivalent to Pythons random.choices()


I'm trying to do choices based on their weight/probability

this is what I had in python:

import random

myChoiceList = ["Attack", "Heal", "Amplify", "Defense"]
myWeights = [70, 0, 15, 15] // % probability = 100% Ex. Attack has 70% of selection

print(random.choices(myChoicelist , weights = myWeights, k = 1))

I want to do the same thing in c#, how does one do that? does C# have any methods similar to random.choices() all I know is random.Next()

*this python code works fine randome.choice takes in (sequence, weights, k) sequence: values, weights: A list were you can weigh the possibility for each value, k: the length of the returned list,

I'm looking to do the same for C#, choose values based on there probability


Solution

  • There is nothing built into C# like this, however, it's not that hard to add an extension method to recreate the same basic behavior:

    static class RandomUtils
    {
        public static string Choice(this Random rnd, IEnumerable<string> choices, IEnumerable<int> weights)
        {
            var cumulativeWeight = new List<int>();
            int last = 0;
            foreach (var cur in weights)
            {
                last += cur;
                cumulativeWeight.Add(last);
            }
            int choice = rnd.Next(last);
            int i = 0;
            foreach (var cur in choices)
            {
                if (choice < cumulativeWeight[i])
                {
                    return cur;
                }
                i++;
            }
            return null;
        }
    }
    

    Then you can call it in a similar way as the Python version:

    string[] choices = { "Attack", "Heal", "Amplify", "Defense" };
    int[] weights = { 70, 0, 15, 15 };
    
    Random rnd = new Random();
    Console.WriteLine(rnd.Choice(choices, weights));