How to make 5 random numbers with sum of 100

前端 未结 8 1623
旧巷少年郎
旧巷少年郎 2020-12-03 13:17

do you know a way to split an integer into say... 5 groups. Each group total must be at random but the total of them must equal a fixed number.

for example I have \"

相关标签:
8条回答
  • 2020-12-03 13:34

    This should do what you need:

    <?php
    $tot = 100;
    $groups = 5;
    $numbers = array();
    for($i = 1; $i < $groups; $i++) {
        $num = rand(1, $tot-($groups-$i));
        $tot -= $num;
        $numbers[] = $num;
    }
    $numbers[] = $tot;
    

    It won't give you a truly balanced distribution, though, since the first numbers will on average be larger.

    0 讨论(0)
  • 2020-12-03 13:40

    Depending on how random you need it to be and how resource rich is the environment you plan to run the script, you might try the following approach.

    <?php
    set_time_limit(10);
    
    $number_of_groups   = 5;
    $sum_to             = 100;
    
    $groups             = array();
    $group              = 0;
    
    while(array_sum($groups) != $sum_to)
    {
        $groups[$group] = mt_rand(0, $sum_to/mt_rand(1,5));
    
        if(++$group == $number_of_groups)
        {
            $group  = 0;
        }
    }
    

    The example of generated result, will look something like this. Pretty random.

    [root@server ~]# php /var/www/dev/test.php
    array(5) {
      [0]=>
      int(11)
      [1]=>
      int(2)
      [2]=>
      int(13)
      [3]=>
      int(9)
      [4]=>
      int(65)
    }
    [root@server ~]# php /var/www/dev/test.php
    array(5) {
      [0]=>
      int(9)
      [1]=>
      int(29)
      [2]=>
      int(21)
      [3]=>
      int(27)
      [4]=>
      int(14)
    }
    [root@server ~]# php /var/www/dev/test.php
    array(5) {
      [0]=>
      int(18)
      [1]=>
      int(26)
      [2]=>
      int(2)
      [3]=>
      int(5)
      [4]=>
      int(49)
    }
    [root@server ~]# php /var/www/dev/test.php
    array(5) {
      [0]=>
      int(20)
      [1]=>
      int(25)
      [2]=>
      int(27)
      [3]=>
      int(26)
      [4]=>
      int(2)
    }
    [root@server ~]# php /var/www/dev/test.php
    array(5) {
      [0]=>
      int(9)
      [1]=>
      int(18)
      [2]=>
      int(56)
      [3]=>
      int(12)
      [4]=>
      int(5)
    }
    [root@server ~]# php /var/www/dev/test.php
    array(5) {
      [0]=>
      int(0)
      [1]=>
      int(50)
      [2]=>
      int(25)
      [3]=>
      int(17)
      [4]=>
      int(8)
    }
    [root@server ~]# php /var/www/dev/test.php
    array(5) {
      [0]=>
      int(17)
      [1]=>
      int(43)
      [2]=>
      int(20)
      [3]=>
      int(3)
      [4]=>
      int(17)
    }
    
    0 讨论(0)
提交回复
热议问题