如果它不等于x,则再次生成随机数

时间:2014-03-02 11:11:42

标签: php random

我想生成1到100之间的数字,但是我想让它继续重新生成那个数字,直到它等于50,一旦它等于50,然后回显它。我该怎么做?

我的功能:

function create() {
    $production_line = mt_rand(0, 3);
    $random1 = mt_rand(0, 9);
    $random2 = mt_rand(0, 9);
    $random3 = mt_rand(0, 9);
    $random4 = mt_rand(0, 9);
    $random5 = mt_rand(0, 9);
    $random6 = mt_rand(0, 9);
    $production_year = mt_rand(3, 4);
    $week1 = 4;
    $week2 = 8;
    $factory1 = 4;
    $factory2 = 8;

    if ($production_line + $random1 + $random2 + $random3 + $random4 + $random5 + $random6 + $production_year + $week1 + $week2 + $factory1 + $factory2 == 55) {
        return $production_line.$random1.$random2.$random3.$random4.$random5.$random6.$production_year.$week1.$week2.$factory1.$factory2;
    }
}

4 个答案:

答案 0 :(得分:6)

使用简单的循环:

$i = 0;
while ($rand = mt_rand(0,100)) {
    $i++;
    if ($rand == 50) {
        // found 50, so break out of the loop
        break;
    }
}

echo "It took $i iterations to find 50";

但这有点无意义,对吧?如果您只是要一直输出50,那么为什么需要生成一个随机数?只需回复50即可。另请注意,如果较大的限制是一个较大的数字,这可能是一个缓慢的操作。

答案 1 :(得分:3)

生成并测试while循环内的所有随机数。

function create() {
    $week1 = 4;
    $week2 = 8;
    $factory1 = 4;
    $factory2 = 8;
    while (true) {
        $production_line = mt_rand(0, 3);
        $random1 = mt_rand(0, 9);
        $random2 = mt_rand(0, 9);
        $random3 = mt_rand(0, 9);
        $random4 = mt_rand(0, 9);
        $random5 = mt_rand(0, 9);
        $random6 = mt_rand(0, 9);
        $production_year = mt_rand(3, 4);

        if ($production_line + $random1 + $random2 + $random3 + $random4 + $random5 + $random6 + $production_year + $week1 + $week2 + $factory1 + $factory2 == 55) {
            return $production_line.$random1.$random2.$random3.$random4.$random5.$random6.$production_year.$week1.$week2.$factory1.$factory2;
        }
    }
}

答案 2 :(得分:3)

我重新安排了一些代码,使其更具凝聚力:

function create() {
    do {
        $arr = [
            mt_rand(0, 3), // line
            mt_rand(0, 9), 
            mt_rand(0, 9),
            mt_rand(0, 9),
            mt_rand(0, 9),
            mt_rand(0, 9),
            mt_rand(0, 9),
            mt_rand(3, 4), // year
            4, // weeks
            8,
            4, // factories
            8,
        ];
    } while (array_sum($arr) != 55);

    return join('', $arr);
}

答案 3 :(得分:2)

$number = 0;
$try = 0;

while ($number != 50) {
  $try++;
  $number = rand(1,100);
}

echo "found $number after $try cycles";