down101102 2011-10-22 17:28
浏览 97
已采纳

基于字符集的固定长度的所有字符串组合

I'm looking to create a function that will return every possible string within a given string length, using a charset.

As an example, a charset of "abc", and a length of 2 should allow for 9 (3 ^ 2) unique combinations:

aa, ab, ac, ba, bb, bc, ca, cb, cc

(List constructed manually)

What method could be used to create such a function?

  • 写回答

2条回答 默认 最新

  • doude2635 2011-10-25 07:23
    关注

    As always, there are multiple ways to solve what you ask for, this is only one way, using one counter per character in the output string:

    $c = "abc"; // charset
    $l = 2; // string length
    
    for($t='',$cl=strlen($c),$s=array_fill(0,$l,0),$i=pow($cl,$l);$a=0,$i--;) {
        for($t&&$t.=', ';$a<$l;$t.=$c[$s[$a++]]);
        for(;$a--&&++$s[$a]==$cl;$s[$a]=0);
    };
    
    echo $t; // the string you asked for.
    

    aa, ab, ac, ba, bb, bc, ca, cb, cc

    One main loop, one loop to build the string and one loop for counting up.

    I can imagine this should work with getting modulos per each position of the output string as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?