php - 生成所有 6 个字符的字母数字组合(大写和小写)

标签 php algorithm combinations

我正在尝试找出一种方法来生成每个可能的 6 字符字母数字字符串的列表,其中大写和小写字母被视为唯一字母。使用以下函数,我们可以使用小写字母和数字生成字符串:

function increasePosition(&$cString, $nPosition) {
    //get the char of the current position
    $cChar = substr($cString, $nPosition - 1, 1);

    //convert to the ascii value (and add one)
    $nChar = ord($cChar) + 1;

    if ($nChar == 58) {
        $nChar = 97; //one past 9, go to a
    }

    if ($nChar == 123) {
        $nChar = 48; //one past z, go to 0
        //we hit z, so increase the next space to the left
        increasePosition($cString, $nPosition - 1);
    }

    //replace the expected position with the new character
    $cString[$nPosition - 1] = chr($nChar);
}

function myCombinations($nSize) {
    //init to 0 repeating.
    $cString = str_repeat('0', $nSize);
    //move the last character 'back' one, so that 0 repeating will be the first item.
    $cString[$nSize - 1] = '/';
    //when to stop.
    $cEnd = str_repeat('z', $nSize);

    while ($cString != $cEnd) {
        increasePosition($cString, $nSize);
        print($cString . " ");
    }
}

myCombinations(2);

Source

但是,这并没有考虑大写字母。在 PHP 的这种算法中是否可以同时使用大写和小写字母?

最佳答案

只需要添加一个小块来处理大写字符:

<?php

function increasePosition(&$cString, $nPosition) {
    //get the char of the current position
    $cChar = substr($cString, $nPosition - 1, 1);

    //convert to the ascii value (and add one)
    $nChar = ord($cChar) + 1;

    if ($nChar == 58) {
        $nChar = 65; //one past 9, go to A
    }

    if ($nChar == 91) {
        $nChar = 97; //one past Z, go to a
    }


    if ($nChar == 123) {
        $nChar = 48; //one past z, go to 0
        //we hit z, so increase the next space to the left
        increasePosition($cString, $nPosition - 1);
    }

    //replace the expected position with the new character
    $cString[$nPosition - 1] = chr($nChar);
}

function myCombinations($nSize) {
    //init to 0 repeating.
    $cString = str_repeat('0', $nSize);
    //move the last character 'back' one, so that 0 repeating will be the first item.
    $cString[$nSize - 1] = '/';
    //when to stop.
    $cEnd = str_repeat('z', $nSize);

    while ($cString != $cEnd) {
        increasePosition($cString, $nSize);
        print($cString . " ");
    }
}

myCombinations(6);

关于php - 生成所有 6 个字符的字母数字组合(大写和小写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881472/

相关文章:

python - 字典集的所有组合成 K 个 N 大小的组

python - 列表列表的排列

Ruby:不要对数组元素进行某些组合

php - 对我在用 PHP 运行的 Web 服务器中缓冲数据有什么建议吗?

php - DOM node.textContent 解析替换

algorithm - 改组和 NRooks 约束保存

php - 购买具有不同购买价格和到期日期的产品的最佳方式是什么?

php - 如何向 Aptana Studio 3 添加 PHP 5.4 语法支持?

php - SQL Order By - 条件不起作用

python - 如何解释 Python 3.x 中的 joblib 回溯?