generate random numbers of which the sum is constant

后端 未结 7 749
暗喜
暗喜 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:39

    yes! try this algorithm

    num1=rand()%20;  
    num2=rand()%(20-num1);  
    num3=rand()%(20-num1-num2);  
    num4=rand()%(20-num1-num2-num3);  
    num5=20-num4-num3-num2-num1;  
    

    so for sure the five numbers are random and they sum up to 20
    [you can do this using loop if you want]

    In general you can first randomly generate the number of numbers[n] that will sum up to the number in hand[K]

     n=rand()%k;--assuming the number of rand numbers you want are between 1 and k[sum]
        n1=rand()%k;
        n2=rand()%(k-n1)
        .
        .
        nn-1=rand()%(k-n1...-nn-2)
        nn=k-n1-n2...nn-1
    

    I hope that will help you!

    0 讨论(0)
提交回复
热议问题