samedi 6 juillet 2019

Increase chance of randomness when running random generator in a loop?

Consider this test code:

function getCode()
{
    $chars = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z');

    $code = '';

    for ($i = 0; $i < 2; $i++)
        $code .= $chars[array_rand($chars)];

    return $code;
}

function saveUnique()
{
    $entries = file('entries.txt');
    static $duplicateCounter = 0;
    $code = getCode();

    if (in_array($code . "\n", $entries)) {
        $duplicateCounter++;
        if ($duplicateCounter < 5)
            saveUnique();
        else {
            exit('<br />duplicate limit reached, giving up...');
        }
    } else {
        file_put_contents('entries.txt', $code . "\n", FILE_APPEND);
        echo $code . " saved<br />";
    }
}

What does is saveUnique() generates a 2-character code and saves it in a text file db. To make sure it's unique, it first checks if it's already in the db. If it is, it tries to generate again up to 5 times before giving up.

Now if you run the ff.:

while(true)
    saveUnique();

You'll notice that it gives up at around +/- 100 attempts.

However, if you try to run it manually, the chance of randomness increases. Try running one separate execution of saveUnique() at a time, outside of a loop, you'll notice it reaches +/- 300 attempts before giving up. E.g., put like this at bottom instead of the while loop:

saveUnique();
?>
<meta http-equiv="refresh" content="1;url=test.php" />

I tried putting mt_srand() inside getCode() but it doesn't seem to make a difference.

Any ideas how to increase chance of randomness when running it in a loop?




Aucun commentaire:

Enregistrer un commentaire