php - 生成带有扭曲的数字字母组合的算法

标签 php algorithm combinations letters-and-numbers

我必须生成一个列表,其中包含长度为 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 (<b>[A-Z0-9]</b>)
letter = 26 possible characters (<b>[A-Z]</b>)
number = 10 possible characters (<b>[0-9]</b>)

36 * 36 * 10 = 12'960 combinations

代码:

<?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

关于php - 生成带有扭曲的数字字母组合的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30332213/

相关文章:

PHP:如何使用 while 循环打印关联数组?

php - 一列上的多个计数值

algorithm - Minimax 的 Alpha-beta 剪枝

c - 有多少矩阵的迹等于 givan 迹?

java - 如何生成给定列表的幂集?

PHP:创建边缘光滑的圆、图像或字体?

php - 在 MySql 数据库表中插入日期?

python - 获取任意长度的列表元素的所有可能 (2^N) 组合

python - python中没有+运算符的求和

algorithm - 给定一个字符串列表,打印所有字符串组合,从每个字符串中选择一个字符