Split value in 24 randomly sized parts using C#

前端 未结 11 1236
忘了有多久
忘了有多久 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:43

    Here's a functional solution using mjv's algorithm:

    static int[] GetSlots(int slots, int max)
    {
        return new Random().Values(1, max)
                           .Take(slots - 1)
                           .Append(0, max)
                           .OrderBy(i => i)
                           .Pairwise((x, y) => y - x)
                           .ToArray();
    }
    
    public static IEnumerable Values(this Random random, int minValue, int maxValue)
    {
        while (true)
            yield return random.Next(minValue, maxValue);
    }
    
    public static IEnumerable Pairwise(this IEnumerable source, Func resultSelector)
    {
        TSource previous = default(TSource);
    
        using (var it = source.GetEnumerator())
        {
            if (it.MoveNext())
                previous = it.Current;
    
            while (it.MoveNext())
                yield return resultSelector(previous, previous = it.Current);
        }
    }
    
    public static IEnumerable Append(this IEnumerable source, params T[] args)
    {
        return source.Concat(args);
    }
    

提交回复
热议问题