在PHP中将单个数字划分为一组唯一的随机数

在PHP中将单个数字划分为一组唯一的随机数,php,Php,我想从一个预先确定的单个数字开始,然后有多个随机数,加起来,它们的总数就是我开始的数字 例如,我有100,但我想有10个随机数,当它们加在一起时,组成100 以我有限的知识,我写了以下内容: <?php $_GET['total'] = $total; $_GET['divided'] = $divided; echo 'Starting with total: ' . $total; echo '<br />'; echo 'Divided between: ' . $div

我想从一个预先确定的单个数字开始,然后有多个随机数,加起来,它们的总数就是我开始的数字

例如,我有100,但我想有10个随机数,当它们加在一起时,组成100

以我有限的知识,我写了以下内容:

<?php
$_GET['total'] = $total;
$_GET['divided'] = $divided;
echo 'Starting with total: ' . $total;
echo '<br />';
echo 'Divided between: ' . $divided;
$randone = rand(1, $total);
$randonecon = $total - $randone;
echo '<br />';
echo 'First random number: ' . $randone;
$randtwo = rand(1, $randonecon);
$randtwocon = $total - $randtwo;
echo '<br />';
echo 'Second random number: ' . $randtwo;
?>

当然,这是一个失败,因为我不知道如何使数字在一个数组中,不让它们超过给定的总数

完全感谢Matei Mihai,完成了

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Randomize</title>
</head>

<body>

<?php

$_GET['total'] = $total;
$_GET['divided'] = $divided;


function generateRandomNumbers($max, $count)
{
$numbers = array();

    for ($i = 1; $i < $count; $i++) {
        $random = mt_rand(0, $max / ($count - $i));
        $numbers[] = $random;
        $max -= $random;
    }

    $numbers[] = $max;

    return $numbers;
}
echo '<pre>'; 
print_r(generateRandomNumbers($total, $divided));
echo '</pre>';

?>


<form id="form1" name="form1" method="get" action="">
  <label for="total">Total</label>
  <br />
  <input type="text" name="total" id="total" />
  <br /> 
   <label for="divided">Divided</label>
  <br />
  <input type="text" name="divided" id="divided" />
  <br />
  <input type="submit" value="Go!">
</form>
</body>
</html>

随机化
全部的


被分割的


您可以尝试使用一个小函数生成以下数字:

Array
(
    [0] => 0
    [1] => 1
    [2] => 6
    [3] => 11
    [4] => 14
    [5] => 13
    [6] => 3
    [7] => 6
    [8] => 13
    [9] => 33
)

请注意,而不是
$random=mt_rand(0,$max/($count-$i))
我可以直接使用
$random=mt_rand(0,$max)
,但在后一种情况下,在结果数组中获得大量0的几率要比第一种情况大。

数字必须是整数吗?如果不是:只需将数字相加,将目标数字除以总和,然后将所有数字与结果相乘。@Franzgleichman是的,它们必须是整数。那么,在按我所述的比例缩放数字之后,必须对它们进行四舍五入,其中一半必须向上四舍五入,一半必须向下四舍五入。这正是我想要的!非常感谢你!直到我替换了:$numbers=[];我才发现代码才起作用;使用$numbers=array();对这是因为从PHP5.4开始就添加了短数组语法,所以您可能使用的版本低于此版本..我现在明白了!这是有帮助的,但我有一个小问题,我们能在数组的任何项中没有零的情况下得到相同的结果吗?
Array
(
    [0] => 0
    [1] => 1
    [2] => 6
    [3] => 11
    [4] => 14
    [5] => 13
    [6] => 3
    [7] => 6
    [8] => 13
    [9] => 33
)