如何使5个随机数总和为100 [英] How to make 5 random numbers with sum of 100

查看:511
本文介绍了如何使5个随机数总和为100的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道一种将整数拆分为... 5组的方法吗? 每个组的总数必须是随机的,但总数必须等于一个固定数字.

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.

例如我有"100",我想将这个数字分成

for example I have "100" I wanna split this number into

1- 20
2- 3
3- 34
4- 15
5- 18

我忘了说是的,保持平衡是一件好事.我想可以通过创建一条if语句来阻止30个以上实例中的任何数字来实现.

i forgot to say that yes a balance would be a good thing.I suppose this could be done by making a if statement blocking any number above 30 instance.

推荐答案

根据所需的随机性以及计划运行脚本的环境的资源丰富程度,您可以尝试以下方法.

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)
}

这篇关于如何使5个随机数总和为100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆