我必须生成长度为3的数字和字母的所有可能组合的列表。问题是前两个字符可以是字母或数字,第三个字符只能是数字。
例如:AA1, AA2, AA3 .... FC7 ... 001, 002 ... 365)
我希望你们都能帮助我。我期待着这些回应。问候,乔希。
到目前为止,我只设法用一种非常简单的方法来获得所有以零为主的数字
for ($k = 0 ; $k < 999; $k++) {
$rnd[] = sprintf('%03d',$k);
}
这应该可以为您工作:
基本上,我有一个包含所有字母([A-Z]
)的数组和一个包含所有数字([0-9]
)的数组。然后定义需要的可能字符的顺序。例如,这里你想要letterNumber
, letterNumber
,然后第三个位置只有number
。
在此之后,你循环遍历所有内容的次数,每个字符的组合,你想要的(例如:XXX -> 3 times
)。在循环中,您将遍历您已经拥有的与当前位置所需的所有字符的所有组合。
所以在第1次迭代之后,你得到了一个数组,其中包含每个组合的第一个字符,即:[0-9A-Z]
.
然后在第二次迭代中,您遍历已经拥有的所有组合,这里[0-9A-Z]
与您想要在第二个位置上的字符,这里[0-9A-Z]
。因此,对于组合数组([0-9A-Z
])中的每个字符,您将获得与[0-9A-Z]
的每个字符的新组合。
如此反复,直到得到期望的组合长度。
所以最后你会得到:
letterNumber = 36 = 26 + 10 possible characters ([A-Z0-9])
letter = 26 possible characters ([A-Z])
number = 10 possible characters ([0-9])
36 * 36 * 10 = 12'960个组合
代码:
<?php
$letters = range("A", "Z");
$numbers = array_merge(range(0, 9));
$order = ["letterNumber", "letterNumber", "number"]; //possibilities: "letter", "number", "letterNumber"
$length = count($order);
$combinations = [[]];
for($count = 0; $count < $length; $count++) {
$tmp = [];
if($order[$count] == "number" || $order[$count] == "letterNumber") {
foreach($combinations as $combination) {
foreach($numbers as $v)
$tmp[] = array_merge($combination, [$v]);
}
}
if($order[$count] == "letter" || $order[$count] == "letterNumber") {
foreach($combinations as $combination) {
foreach($letters as $v)
$tmp[] = array_merge($combination, [$v]);
}
}
$combinations = $tmp;
}
print_r($combinations);
?>
输出:Array
(
[0] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
[1] => Array
(
[0] => 0
[1] => 0
[2] => 1
)
//...
[12959] => Array
(
[0] => Z
[1] => Z
[2] => 9
)
)
演示下面的代码可以完美地满足我的要求。
$letters = range('A', 'Z');
$comb = array();
for ($k = 0 ; $k <= 9; $k++) {
foreach($letters as $l){
foreach($letters as $le){
$comb[]= $l.$le.$k;
}
}
}
for ($k = 0 ; $k <= 999; $k++) {
$comb[] = sprintf('%03d',$k);
}