Generating unique 6 digit code

前端 未结 6 2100
鱼传尺愫
鱼传尺愫 2020-12-28 10:06

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)

6条回答
  •  难免孤独
    2020-12-28 10:56

    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 :(

提交回复
热议问题