gpt4 book ai didi

php - 在PHP中将单个数字分成一组唯一的随机数

转载 作者:行者123 更新时间:2023-12-04 12:50:08 24 4
gpt4 key购买 nike

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

例如,我有 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>

最佳答案

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

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

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

$numbers[] = $max;

shuffle($numbers);

return $numbers;
}

echo '<pre>';
print_r(generateRandomNumbers(100, 10));
echo '</pre>';

该函数将生成如下数组:

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 的机会比第一种情况大。

关于php - 在PHP中将单个数字分成一组唯一的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40088263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com