generate random numbers of which the sum is constant

后端 未结 7 763
暗喜
暗喜 2020-12-03 15:40

I am thinking if there is anyway to generate a set of random numbers of which the sum is always a constant. For example, 20 can be divided into 5 numbers ( 1, 2,3,4,10) I do

7条回答
  •  星月不相逢
    2020-12-03 16:28

    Use a library function to get the random numbers.

    Now the random number you want is the generated random number mod the allowed sum.

    Next you decrement the allowed sum by the number you just generated.

    Let's say the first random number your library random number generator returns is 109.

    So your first random number is 109 mod 20 = 9. Update your allowed total to 20 -9 = 11.

    You keep going until your allowed sum is zero.

    Note that I assume the number 5 you mentioned is just an example. If you want the number of random numbers to be exactly 5 you might have to modify this method.

提交回复
热议问题