13

私はこれを持っています:

<?php  $n = rand(1,1600); echo $n ?>

234、1578、763、1274 などの乱数を除外したいと思います。どうすればいいですか?

4

10 に答える 10

14
<?php

while( in_array( ($n = mt_rand(1,1600)), array(234, 1578 ,763 , 1274) ) );
于 2013-06-14T13:24:54.363 に答える
11

このようにしてみてください

do {   
    $n = rand(1,1600);

} while(in_array($n, array(234, 1578 ,763 , 1274 ));
echo $n;
于 2013-06-14T13:23:08.697 に答える
8

番号が不要なものかどうかを確認し、新しい乱数を取得する場合。

function getRandomNumber() {
    do {
        $n = mt_rand(1,1600);
    } while(in_array($n, array(234,1578, 763, 1274)));

    return $n;
}
于 2013-06-14T13:23:34.987 に答える
1

または、ランダムな (場合によっては無限の) 実行時間でループを作成しないようにします。

/**
 * 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;
}

この関数は、ランダムな位置を選択し、除外配列をたどって自由な位置を見つけます。実行時間は、除外する数値の量によって異なります。特定の範囲を除外したい場合は、これを考慮してアルゴリズムを適応させることができます。

于 2014-05-29T01:10:48.663 に答える
0

有効な数値で配列を作成できます。

次に、乱数生成により、インデックスがその配列に返されます。

于 2013-06-14T13:24:33.603 に答える
0

除外する数が多すぎない場合は、不要な数が見つかった場合に再試行する方が簡単で高速です。

$n = 0;
while (in_array($n, array(0, 234, 1578 ,763 , 1274))) {
  $n = rand(1,1600); 
}

echo $n;
于 2013-06-14T13:24:44.773 に答える