Split value in 24 randomly sized parts using C#

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

    This is fun. Inspired by David, here's an implementation of mjv's solution using only LINQ-provided operators. Since David's Dictionary key is just an index, we can use an array instead for the Pairwise functionality:

    var r = new Random();
    var a = Enumerable.Repeat(null, n - 1)        // Seq with (n-1) elements...
                      .Select(x => r.Next(1, m))  // ...mapped to random values
                      .Concat(new [] { 0, m })
                      .OrderBy(x => x)
                      .ToArray();
    
    return a.Skip(1).Select((x,i) => x - a[i]);
    

提交回复
热议问题