Split value in 24 randomly sized parts using C#

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

    Another option would be to generate a random number between 0 and the target number. Then, add each "piece" to a list. Choose the largest "piece" and cut it in two, using another random number. Select the largest from the list (now with three pieces), and continue until you have the desired number of pieces.

    List list = new List();
    list.Add(2010);
    Random random = new Random();
    while (list.Count() < 24)
    {
        var largest = list.Max();
        var newPiece = random.Next(largest - 1);
        list.Remove(largest);
        list.Add(newPiece);
        list.Add(largest - newPiece);
    }
    

提交回复
热议问题