down101102 2011-10-23 01: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 15: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条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写