私はこれを持っています:
<?php $n = rand(1,1600); echo $n ?>
234、1578、763、1274 などの乱数を除外したいと思います。どうすればいいですか?
私はこれを持っています:
<?php $n = rand(1,1600); echo $n ?>
234、1578、763、1274 などの乱数を除外したいと思います。どうすればいいですか?
<?php
while( in_array( ($n = mt_rand(1,1600)), array(234, 1578 ,763 , 1274) ) );
このようにしてみてください
do {
$n = rand(1,1600);
} while(in_array($n, array(234, 1578 ,763 , 1274 ));
echo $n;
番号が不要なものかどうかを確認し、新しい乱数を取得する場合。
function getRandomNumber() {
do {
$n = mt_rand(1,1600);
} while(in_array($n, array(234,1578, 763, 1274)));
return $n;
}
または、ランダムな (場合によっては無限の) 実行時間でループを作成しないようにします。
/**
* Returns a random integer between $min and $max (inclusive) and
* excludes integers in $exarr, returns false if no such number
* exists.
*
* $exarr is assumed to be sorted in increasing order and each
* element should be unique.
*/
function random_exclude($min, $max, $exarr = array()) {
if ($max - count($exarr) < $min) {
return false;
}
// $pos is the position that the random number will take
// of all allowed positions
$pos = rand(0, $max - $min - count($exarr));
// $num being the random number
$num = $min;
// while $pos > 0, step to the next position
// and decrease if the next position is available
for ($i = 0; $i < count($exarr); $i += 1) {
// if $num is on an excluded position, skip it
if ($num == $exarr[$i]) {
$num += 1;
continue;
}
$dif = $exarr[$i] - $num;
// if the position is after the next excluded number,
// go to the next excluded number
if ($pos >= $dif) {
$num += $dif;
// -1 because we're now at an excluded position
$pos -= $dif - 1;
} else {
// otherwise, return the free position
return $num + $pos;
}
}
// return the number plus the open positions we still had to go
return $num + $pos;
}
この関数は、ランダムな位置を選択し、除外配列をたどって自由な位置を見つけます。実行時間は、除外する数値の量によって異なります。特定の範囲を除外したい場合は、これを考慮してアルゴリズムを適応させることができます。
有効な数値で配列を作成できます。
次に、乱数生成により、インデックスがその配列に返されます。
除外する数が多すぎない場合は、不要な数が見つかった場合に再試行する方が簡単で高速です。
$n = 0;
while (in_array($n, array(0, 234, 1578 ,763 , 1274))) {
$n = rand(1,1600);
}
echo $n;