Distributed probability random number generator

前端 未结 7 1048
挽巷
挽巷 2020-12-05 10:47

I want to generate a number based on a distributed probability. For example, just say there are the following occurences of each numbers:

Number| Count               


        
7条回答
  •  遥遥无期
    2020-12-05 11:13

    Use my method. It is simple and easy-to-understand. I don't count portion in range 0...1, i just use "Probabilityp Pool" (sounds cool, yeah?)

    At circle diagram you can see weight of every element in pool

    Here you can see an implementing of accumulative probability for roulette

    `
    
    // Some c`lass or struct for represent items you want to roulette
    public class Item
    {
        public string name; // not only string, any type of data
        public int chance;  // chance of getting this Item
    }
    
    public class ProportionalWheelSelection
    {
        public static Random rnd = new Random();
    
        // Static method for using from anywhere. You can make its overload for accepting not only List, but arrays also: 
        // public static Item SelectItem (Item[] items)...
        public static Item SelectItem(List items)
        {
            // Calculate the summa of all portions.
            int poolSize = 0;
            for (int i = 0; i < items.Count; i++)
            {
                poolSize += items[i].chance;
            }
    
            // Get a random integer from 0 to PoolSize.
            int randomNumber = rnd.Next(0, poolSize) + 1;
    
            // Detect the item, which corresponds to current random number.
            int accumulatedProbability = 0;
            for (int i = 0; i < items.Count; i++)
            {
                accumulatedProbability += items[i].chance;
                if (randomNumber <= accumulatedProbability)
                    return items[i];
            }
            return null;    // this code will never come while you use this programm right :)
        }
    }
    
    // Example of using somewhere in your program:
            static void Main(string[] args)
            {
                List items = new List();
                items.Add(new Item() { name = "Anna", chance = 100});
                items.Add(new Item() { name = "Alex", chance = 125});
                items.Add(new Item() { name = "Dog", chance = 50});
                items.Add(new Item() { name = "Cat", chance = 35});
    
                Item newItem = ProportionalWheelSelection.SelectItem(items);
            }
    

提交回复
热议问题