generate random numbers of which the sum is constant

后端 未结 7 762
暗喜
暗喜 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:25

    If the numbers Generated are not necesserily Positive or whitin a range.
    you can calculate the last number can be S - SUM(A1..A[N-1])

    Selection of N-1 random numbers is obviously uniform,
    and because the last number is anyway dependent on the rest of the numbers
    (each set has only one option for the last number).

    the uniformitty is not hindered.

    Arr = new int[N];
    
    int sum=0;
    for(i=0; i

提交回复
热议问题