Page 1 of 1

How to create unique numbers

Posted: Mon Jan 04, 2010 11:47 pm
by gimpact
Hello,

I am trying to create a 4 digit unique number every time, i run my code. To make this happen, I am storing the unique numbers into a database and while creating next unique id, i am making a check with the existing numbers to get a unique number.

So far with my code. I am able to get a 4 digit unique number. I am also able to check it with the database. The problem that I am facing due to my limited knowledge of programming or php, is that, once the number is found to be existing. I am not able to get my logic quite correctly, how to regenerate the number.

I understand this could be done by WHILE loop. So here is my try. Please help me to correct this code.

Code: Select all

 
function validateRandomID($random_id){
        $query = "SELECT * FROM shortURL WHERE randomID = '$random_id'";
        $query2 = mysql_query($query) or die("Cannot check for id " . mysql_error());
        $query3 = mysql_fetch_array($query2);
 
        if(strlen($query3['randomID'])>0){
            $length = 4;
            // Try to regenerate the number
            $random_id = get_rand_id($length); // The function which creates the unique IDs
            // Check Random number for uniqueness
            $random_id = validateRandomID($random_id); // Calling this function again
            return $random_id; 
            
        }else{
            return $random_id;
        }
  
        return $random_id;
    }
Thank you.

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 12:11 am
by Christopher
Yikes ... as your table fills up you will have to do thousands of queries to find another number. It would make more sense to just use autoincrement and sequential numbers.

I guess you could create a table with 10,000 numbers randomized. Probably fastest in MySQL to generate a text file (with sequential #, random # columns) and then LOAD DATA INFILE.

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 12:22 am
by manohoo
If what you want is just 4 unique random numbers....

Code: Select all

<?php
 
function generateNumbers($n=4)
{
  $rs = array(); //stores numbers
  for ($i=0;$i<$n;$i++)
  {
    $a = rand(1000,9999);
    if (in_array($a,$rs)) {$i--;}
    else {$rs[] = $a;}
  }
  return $rs;
}
 
$z = generateNumbers();
foreach ($z as $row) {echo $row."<br />";}
?>
Output:
1116
5944
5077
9363

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 3:17 am
by gimpact
Thank you, I am looking for a mixture of numbers and alphabets. What you have shown can at times generate the same number twice. I am looking for a full proof 4 digit alpha numeric number.

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 5:19 am
by timWebUK
Generate a random number, append the current timestamp to it. Then hash it. And truncate it to just the first 4 characters?

Although this would be unique for the whole hash, when truncated, there are chances of duplication. Especially with only 4 characters. So you would need to check anyway. I think you should just do it sequentially to guarantee unique numbers... perhaps when you get 9999, add letters. a999, b999 etc.

And I believe 4 digits, alphanumeric would give 4^37 combinations... is this right anyone?

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 5:23 am
by Apollo
Note this:

Code: Select all

if (in_array($a,$rs)) {$i--;}
So no, it won't produce the same number twice.

To generate random alphanumerical strings, you can use all kinds of approaches. You could use the chr and mt_rand functions, for example:

Code: Select all

$x = mt_rand(0,35);
$c = chr((($x<10) ? ord('0') : ord('a')-10) + $x); // $c is now one random char 0-9 or a-z
Or you could do something like

Code: Select all

$s = '0123456789abcdefghijklmnopqrstuvwxyz';
$c = $s[ mt_rand(0,35) ];
Concatenate 4 of these chars and use a method of your choice to avoid duplicates.


timWebUK, it's 36^4 = 1,679,616

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 7:37 am
by timWebUK
Apollo wrote:timWebUK, it's 36^4 = 1,679,616
Ha, I'm an idiot!

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 1:17 pm
by manohoo
I am looking for a mixture of numbers and alphabets
That's not what you said in your original post.
I am looking for a full proof 4 digit alpha numeric number.
What you want does not exist. There's not such a thing as an alpha numeric number in the decimal numbering system.
What you have shown can at times generate the same number twice
No, they are unique. Apollo already answered you on this one.

Re: How to create unique numbers

Posted: Tue Jan 05, 2010 7:30 pm
by Christopher
gimpact wrote:I am looking for a full proof 4 digit alpha numeric number.
Generate however many numbers you want sequentially in base 36. You can step by some value if you want more variety. Shuffle the array if you like. That just might be fool proof -- but you can never guarantee that.

Here is a very quick hack:

Code: Select all

$num_codes = 100;
$step = 1700000 / $num_codes;
$number = 40000 + rand(10000, 20000);
$codes = array();
for ($i=1; $i<=$num_codes; ++$i) {
    $codes[$i] = base_convert($number, 10, 36);
    $number += $step;
}
shuffle($codes);
var_dump($codes);

Re: How to create unique numbers

Posted: Wed Jan 06, 2010 3:13 am
by gimpact
Thank you. Since a combination of characters and numbers will give me more choices. I decided to go for a combination of numbers and characters.

I am sure that, as I reach closer to 1,679,616 my codes will begin to generate strings which has already been used. So, my plan is to use a database for checking uniqueness of a string.

With all that I have done, I am actually able to generate an unique string of numbers and characters but when I find the number is existing. I am so blind and dont know how to run a while loop for say 50 times at the maximum to regenerate the number again and check for uniqueness.

I am sorry, if i am not very clear in my post.

Thank you.

Re: How to create unique numbers

Posted: Wed Jan 06, 2010 3:25 am
by Apollo
I'm sure someone can help you here, but if you don't know how to run a while loop for at most 50 times, you may really be better off by working through a PHP beginner's tutorial first.