Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Random Number but not 2

Why is it this sometimes returns 2?

function pickServer(){
    $varr = rand(1,4);
    if($varr==2){
        pickServer();
    }
    return $varr;
}
like image 230
Abs Avatar asked Aug 19 '09 15:08

Abs


3 Answers

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.

like image 163
Nosredna Avatar answered Oct 06 '22 00:10

Nosredna


Because you're not stopping the function there. the fourth line should read:

return pickServer();
like image 20
nickf Avatar answered Oct 05 '22 23:10

nickf


Another way to do it is using do … while:

function pickServer() {
    do {
        $varr = rand(1,4);
    } while ($varr == 2);
    return $varr;
}
like image 31
Gumbo Avatar answered Oct 06 '22 00:10

Gumbo