【问题标题】:Generating all 6 character alphanumeric combinations (upper and lower case)生成所有 6 个字符的字母数字组合(大写和小写)
【发布时间】:2015-11-23 21:57:04
【问题描述】:

我正在尝试找出一种方法来生成每个可能的 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中这种算法可以同时使用大写和小写字母吗?

【问题讨论】:

  • 只添加大写的ascii代码范围
  • (26+26+10)^6 数据量很大
  • @Steve 是的,这些将被存储为一个文件名池以供从中获取。
  • 您需要十亿个文件名?哇
  • 自动增量 ID 或其中一种独特的功能会更容易。

标签: php algorithm combinations


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2011-01-16
    • 2016-07-12
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多