Distributed probability random number generator

前端 未结 7 1051
挽巷
挽巷 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:06

    Thanks for all your solutions guys! Much appreciated!

    @Menjaraz I tried implementing your solution as it looks very resource friendly, however had some difficulty with the syntax.

    So for now, I just transformed my summary into a flat list of values using LINQ SelectMany() and Enumerable.Repeat().

    public class InventoryItemQuantityRandomGenerator
    {
        private readonly Random _random;
        private readonly IQueryable _quantities;
    
        public InventoryItemQuantityRandomGenerator(IRepository database, int max)
        {
            _quantities = database.AsQueryable()
                .Where(x => x.Quantity <= max)
                .GroupBy(x => x.Quantity)
                .Select(x => new
                                 {
                                     Quantity = x.Key,
                                     Count = x.Count()
                                 })
                .SelectMany(x => Enumerable.Repeat(x.Quantity, x.Count));
    
            _random = new Random();
        }
    
        public int Next()
        {
            return _quantities.ElementAt(_random.Next(0, _quantities.Count() - 1));
        }
    }
    

提交回复
热议问题