mercredi 1 juillet 2015

10 digit mt_rand() with unbiased first digit

I want to generate the profile ids in my software. The mt_rand function works well but I need the ids to be a fixed 10 digit long. Currently I am looping through mt_rand outputs until I get a 10 digit number. But the problem I am facing now is that most of the profile ids start from 1 and some from 2. None from any of the other single digit numbers. I understand this happens because of mt_rand's range and it can't produce 10 digit numbers that start with 3 or more.

This is what I am currently doing

for($i = 0; $i < 200; $i++){
    $num = mt_rand();
    if(strlen($num) == 10) echo $num."<br>";
}

If you run the above code you will see all numbers start from either 1 or 2. Any way to fix this?

Edit: I guess I can just flip the numbers but some numbers end with zero and this seems like a bit of a hack anyways. But then again, random number generation is a hack in itself I guess.




Aucun commentaire:

Enregistrer un commentaire