Generating unique codes that are different in two digits

I want to generate unique code numbers (composed of 7 digits exactly). The code number is generated randomly and saved in MySQL table.

I have another requirement. All generated codes should differ in at least two digits. This is useful to prevent errors while typing the user code. Hopefully, it will prevent referring to another user code while doing some operations as it is more unlikely to miss two digits and match another existing user code.

The generate algorithm works simply like:

  1. Retrieve all previous codes if any from MySQL table.
  2. Generate one code at a time.
  3. Subtract the generated code with all previous codes.
  4. Check the number of non-zero digits in the subtraction result.
  5. If it is > 1, accept the generated code and add it to previous codes.
  6. Otherwise, jump to 2.
  7. Repeat steps from 2 to 6 for the number of requested codes.
  8. Save the generated codes in the DB table.

The algorithm works fine, but the problem is related to performance. It takes a very long to finish generating the codes when requesting to generate a large number of codes like: 10,000.

The question: Is there any way to improve the performance of this algorithm?

I am using perl + MySQL on Ubuntu server if that matters.

7
задан toolic 21 March 2011 в 16:18
поделиться