Why is it this sometimes returns 2?
function pickServer(){
$varr = rand(1,4);
if($varr==2){
pickServer();
}
return $varr;
}
The answer to your question, as others have pointed out, is that your code falls through without returning. If 2
is returned by the call to rand() on both the first attempt and the second attempt (there's a 1/16 chance of this happening), you'll get 2
as a result.
But your approach to solving the problem could be better.
Both recursion and looping are barmy for this problem. This is a mapping problem, not a randomness problem. (It resembles some common randomness coding interview problems which can be handled most easily in a rejection loop, but it really isn't a problem of that class.)
You want one of three outcomes, not four. (1, 3, and 4.) That means you should be generating a range of three random numbers, not four. You could remap with an array or use an if
. Both possibilities are shown below. Let me know if I have syntax wrong--my PHPfu is weak this morning.
/* 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;
}
I didn't notice it before, but balpha anticipated my answer. He remapped with an if
in his second example. Instead of remapping 2 to 4, he just added one to any answer above 1, which is an equivalent solution.
Because you're not stopping the function there. the fourth line should read:
return pickServer();
Another way to do it is using do … while
:
function pickServer() {
do {
$varr = rand(1,4);
} while ($varr == 2);
return $varr;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With