私はあらかじめ決められた単一の数字で始めたいが、合計したときにその合計が私が始めた数である複数の乱数を持つ。PHPで一意の乱数のセットに単一の数字を分割する
<?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;
?>
の:
は、例えば、私は100を持っていますが、彼らは一緒に追加されたときに、私の限られた知識で100
を作ることを10個の乱数を持つようにしたい、私はこれを書きましたもちろん、それは失敗です。数字を、与えられた合計を超えないような配列にする方法がわからないからです。
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>
数字は整数でなければなりませんか?そうでない場合は、あなたの番号を追加し、あなたの*ターゲット番号*を合計で除算し、すべての数字に結果を掛けます。 –
@FranzGleichmannはい、整数である必要があります。 –
井戸 - 記述したような数字を拡大した後、丸めなければならない。半分は切り上げ、半分は切り捨てる必要がある。 –