1

I have to generate a list of all possible combinations of numbers and letters of length three. The catch is on the first two characters can be letters or numbers, and the third one can only be numeric.

For example:

AA1, AA2, AA3 .... FC7 ... 001, 002 ... 365)

I hope you can all help me. I look forward to these responses. Regards, Josh.

So far i only managed a very simple way to get all number with prevailing zeros

for ($k = 0 ; $k < 999; $k++) {
     $rnd[] = sprintf('%03d',$k);
}
4

2 回答 2

2

这应该适合你:

基本上我有一个包含所有字母 ( [A-Z]) 的数组和一个包含所有数字 ( [0-9]) 的数组。然后你定义你想要的可能字符的顺序。例如在这里你想要letterNumberletterNumber然后只有第三个点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
        )

)

Demo

于 2015-05-19T17:48:39.750 回答
1

以下代码非常适合我所追求的。

$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);
}
于 2015-05-19T17:41:56.060 回答