Answer the question
In order to leave comments, you need to log in
Generation of a unique combination by means of php?
It is required to generate a unique combination.
The combination consists of 16 digits
, each digit is in the range from 1 to 10.
Example: 1 9 2 6 10 9 3 7 1 3 9 10 3 6 10 2
Played with mt_srand() and other things. I haven't been able to find an ideal solution.
10^16 shows a very large number of possible combinations (if I remember the school computer science course). But when there are 16k duplicates for 50k, this is nothing. In the most stupid random, it turned out to be 10k - 200 duplicates.
The field with the combination has a unique index in the base, so I really don't want to skip combinations. Or at least reduce the number of duplicates to a minimum.
What are the generation options?
Answer the question
In order to leave comments, you need to log in
You must understand that random values are random, they are repeated and cannot be generated for unique fields. Use autoincrement.
Obviously, pseudo-random numbers are not the best way to get a unique key.
But essentially this is the code:
function getRandSeq($seq_len) {
$result = array();
for ($i=1; $i<=$seq_len; $i++)
$result[] = rand(1, 10);
return implode(" ", $result);
}
function getMtRandSeq($seq_len) {
$result = array();
for ($i=1; $i<=$seq_len; $i++)
$result[] = mt_rand(1, 10);
return implode(" ", $result);
}
//
$total = 50000;
$seq_arr1 = array();
$seq_arr2 = array();
$dbl_count1 = 0;
$dbl_count2 = 0;
for ($t=1; $t<=$total; $t++) {
$seq1 = getRandSeq(16);
$seq2 = getMtRandSeq(16);
if (in_array($seq1, $seq_arr1))
$dbl_count1++;
if (in_array($seq2, $seq_arr2))
$dbl_count2++;
$seq_arr1[] = $seq1;
$seq_arr2[] = $seq2;
}
echo $dbl_count1."/".$dbl_count2."/".$total;
Is it possible to use the UUID function ?
True, the format may not be suitable.
Option 2, not productive, generating a number in a cycle with requests for uniqueness to the database, not unique, so we generate a new one.
Try generating numbers from 10^15 to 10^16-1 instead of combinations.
entropy in Unixes is in /dev/random
, however, its quantity is limited, you have to wait
or use /dev/urandom
you need to get not 16 numbers from 1 to 10, but one sequence of about 50 bits long (that is, it will turn out 50-digit number with base 2, it can be converted to a number with base 10)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question