加速生成N个唯一的随机数代码

时间:2012-08-03 20:48:19

标签: php

我被要求在AA0000-ZZ9999范围内生成所有可能的组合(我们称之为folio),对于每个组合,我还需要一个8位数的唯一ramdom数字(让我们称之为{{1} }),不能连续,我知道有很多组合,而且过程会很慢,但是当我使用attcode函数时,我要验证每个{{1必须是唯一的,它使我的代码变慢,所以如果可能(我知道它是,只是不知道如何),给我建议'回合我怎样才能在我的代码中改进它

rand

2 个答案:

答案 0 :(得分:2)

好的,这次我完全破解了。我对这个问题实际上有点满意:

// An array of 10000 0's
$attcodes1 = array_fill(0, 9999, 0);

// An array of 10000 from 0 - 9999
$attcodes2 = range(0, 9999);
// Not actually necessary but makes $attcodes appear more random
shuffle($attcodes2);

// Loop until the alphas roll over to 3 characters
for ($alpha = "AA", $num = 0; $alpha != 'AAA'; $num++) {
  if ($num == 1001) {
    $num = 0; // At 1000 reset the counter to 0
    $alpha++; // Roll over to next alpha sequence
  }
  $folio = sprintf("$alpha%04s", $num); // Generate folio

  // Here's the clever bit, if I do say so myself...
  // Loop while we are hitting 4 digit sequences that have used every other
  // possible 4 digit sequence and remove them from the options.
  // This is *very* unlikely to loop more than twice, if ever
  while ($attcodes1[$part1 = array_rand($attcodes1)] >= 9999) {
    array_splice($attcodes1, $part1, 1);
  }
  // Get a 4 digit sequence not used with $part1 before and make sure we never
  // get it again (increment counter)
  $part2 = $attcodes2[$attcodes1[$part1]++];
  // Now it just needs stitching together and left-padding with 0s
  $attcode = sprintf("%04s%04s", $part1, $part2);

  // Job done
  echo $folio.'-'.$attcode."\n";

}

...并且没有疯狂的内存使用,我的早期尝试正在产生。严重的是,在PHP中存储32位( 4字节!)整数需要 24字节

看看我的(相当低规格)笔记本电脑的进展情况,我估计从开始到结束都有10分钟的运行时间。如果您不动态回显结果,这将大大减少。我认为。虽然我不确定你用它们做什么而不会烧毁内存或卡在磁盘I / O上。

答案 1 :(得分:0)

我已经完成了一项功能,请完成它

function fnGetRandomNumber($intLength = 6) 
{
  $arrAlphNumeric = array("c","d"); 
  $arrCharacters = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"); 
  $arrNumbers = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); 
  $strNewNumber = ""; 
  $intCountNumberLength = 1; 
  do { 
     $strValue = $arrAlphNumeric[rand(0,1)]; 
     if($strValue == "c") { 
        $strNewNumber .= $arrCharacters[rand(0,25)]; 
      } else { 
        $strNewNumber .= $arrNumbers[rand(0,9)]; 
      } 
        $intCountPasswordLength++; 
    } while($intNumberLength >= $intCountNumberLength); 

    return $strNewNumber; 
}