Return random number, but not 2

Why does this sometimes return 2?

function pickServer(){
    $varr = rand(1,4);
    if($varr==2){
        pickServer();
    }
    return $varr;
}
+5
source share
10 answers

Because you do not stop the function there. the fourth line should read:

return pickServer();
+19
source

The answer to your question, as others have pointed out, is that your code fails without returning. If it 2returns by calling rand () both on the first attempt and on the second attempt (there is a 1/16 probability of this case), you will get 2the result.

But your approach to solving the problem could be better.

, . , . ( , , .)

, . (1, 3 4.) , , . if. . , - PHPfu .

/* array remapping */
function pickServer() {
    $remap = array(1, 3, 4);
    return $remap[rand(1,3)];
}

/* if remapping */
function pickServer() {
    $server = rand(1,3);
    if ($server==2) {
        $server=4;
    }
    return $server;
}

, . if . , 2-4, 1, .

+26

- do … while:

function pickServer() {
    do {
        $varr = rand(1,4);
    } while ($varr == 2);
    return $varr;
}
+13

, , ,

function pickServer(){
  $varr = rand(1,4);
  if($varr==2){
    $varr = pickServer();
  }
  return $varr;
}

- , , . , - :

function pickServer(){
  $varr = rand(1,3);
  if($varr > 1){
    $varr = $varr + 1;
  }
  return $varr;
}
+10

, 2, pickserver. $varr.

+2
function pickServer(){
    $varr = rand(1,4);
    if($varr==2){
        return pickServer(); //leave here
    }
    return $varr;
}
+2

:

function pickServer()
{
$servers = array(1,3,4);
return $servers[rand(1,count($servers))]; 
}
+1

, , 2, .

Try changing pickServer () to return pickServer () .

Better yet, write the function iteratively so that it just loops until the return value is 2.

0
source

You forgot to return the value ...

function pickServer(){
$varr = rand(1,4);
if($varr==2){
    return pickServer();
}
return $varr;
}
0
source

You can delete the recursion and reassign the randomly selected 2. Just reduce the range and draw the beginning of the range (in this case 2) to 1.

function pickServer(){
    $varr = rand(2,4);
    if($varr==2){
        return 1;
    }
    return $varr;
}
0
source

All Articles