Split value in 24 randomly sized parts using C#

前端 未结 11 1176
忘了有多久
忘了有多久 2021-02-03 12:01

I have a value, say 20010. I want to randomly divide this value over 24 hours. So basically split the value into a 24 slot big array where all slots are randomly big.

Wh

11条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-03 12:17

    Here's another solution that I think would work very well for this. Each time the method is called, it will return another set of randomly distributed values.

    public static IEnumerable Split(int n, int m)
    {
        Random r = new Random();
        int i = 0;
    
        var dict = Enumerable.Range(1, m - 1)
            .Select(x => new { Key = r.NextDouble(), Value = x })
            .OrderBy(x => x.Key)
            .Take(n - 2)
            .Select(x => x.Value)
            .Union(new[] { 0, m })
            .OrderBy(x => x)
            .ToDictionary(x => i++);
    
        return dict.Skip(1).Select(x => x.Value - dict[x.Key - 1]);
    }
    

提交回复
热议问题