Split value in 24 randomly sized parts using C#

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

    This will give you a somewhat "decreasing" randomness the higher the index becomes. You can randomise the list positions if required? It depends on what you need to do with it.

    int initialValue = 20010;
    var values = new List();
    
    Random rnd = new Random();
    int currentRemainder = initialValue;
    
    for (int i = 0; i < 21; i++)
    {
        //get a new value;
        int val = rnd.Next(1, currentRemainder - (21 - i));
    
        currentRemainder -= val;
        values.Add(val);
    }
    
    values.Add(currentRemainder);
    
    //initialValue == values.Sum()
    

提交回复
热议问题