0

我被要求生成 AA0000-ZZ9999 范围内的所有可能组合(我们称之为folio),对于每个组合我还需要一个 8 位唯一随机数(我们称之为attcode),不能连续,我知道有有很多组合,过程会很慢,但是当我使用该rand函数时,我必须验证每个attcode都必须是唯一的,这会使我的代码变慢,所以如果可能的话(我知道是,只是不知道如何),给我建议'关于如何在我的代码中改进它

$alph = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1);
$code_cache = array();
foreach ($alph as $value1) {
  foreach ($alph as $value2) {
    for ($i = 0; $i <= 9; $i++) {
        $n=$i;
        if($i<10){
            $n="000".$i;
        }
        elseif($i<100){
            $n="00".$i;
        }
        elseif($i<1000){
            $n="0".$i;
        }
        $code = rand(10000000, 99999999);
        while(in_array($code, $code_cache)){
            $code = rand(10000000, 99999999);
        }
        $code_cache[]=$code;
        echo $value1.$value2.$n.'-'.$code.'<br/>';
    }
  }
}
4

2 回答 2

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 上。

于 2012-08-03T21:19:27.307 回答
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; 
} 
于 2012-12-28T17:57:57.837 回答