Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique 6 digit code

I'm generating a 6 digit code from the following characters. These will be used to stamp on stickers.
They will be generated in batches of 10k or less (before printing) and I don't envisage there will ever be more than 1-2 million total (probably much less).
After I generate the batches of codes, I'll check the MySQL database of existing codes to ensure there are no duplicates.

// exclude problem chars: B8G6I1l0OQDS5Z2

$characters = 'ACEFHJKMNPRTUVWXY4937';

$string = '';

for ($i = 0; $i < 6; $i++) {
    $string .= $characters[rand(0, strlen($characters) - 1)];
}   

return $string;
  1. Is this a solid approach to generating the code?
  2. How many possible permutations would there be? (6 Digit code from pool of 21 characters). Sorry math isn't my strong point
like image 685
Quad6 Avatar asked May 09 '13 23:05

Quad6


People also ask

How do I get a unique 6 digit code?

If you want to fake randomness you can use the following: Reduce to 19 possible numbers and make use of the fact that groups of order p^k where p is an odd prime are always cyclic. Take the group of order 7^19, using a generator co-prime to 7^19 (I'll pick 13^11, you can choose anything not divisible by 7).

How many unique 6 digit numbers are there?

∴ In total, there are 900,000 6-digit numbers.

How many 6 digit numbers can be formed from the digits?

Hence, the correct answer is 720.


1 Answers

21^6 = 85766121 possibilities.

Using a DB and storing used values is bad. If you want to fake randomness you can use the following:

Reduce to 19 possible numbers and make use of the fact that groups of order p^k where p is an odd prime are always cyclic.

Take the group of order 7^19, using a generator co-prime to 7^19 (I'll pick 13^11, you can choose anything not divisible by 7).

Then the following works:

$previous = 0;

function generator($previous)
{

  $generator = pow(13,11);
  $modulus = pow(7,19); //int might be too small
  $possibleChars = "ACEFHJKMNPRTUVWXY49";

  $previous = ($previous + $generator) % $modulus;
  $output='';
  $temp = $previous;

  for($i = 0; $i < 6; $i++) {
    $output += $possibleChars[$temp % 19];
    $temp = $temp / 19;
  }

  return $output;
}

It will cycle through all possible values and look a little random unless they go digging. An even safer alternative would be multiplicative groups but I forget my math already :(

like image 130
Jean-Bernard Pellerin Avatar answered Sep 26 '22 15:09

Jean-Bernard Pellerin