duanhuanbo5225 2013-03-29 17:08
浏览 90
已采纳

PHP列出所有可能的具有特定数字的6位数字[重复]

This question already has an answer here:

How could I generate every possible number of a given amount of digits and using specific digits?

So basically, I would like to have a 6 digit number for example using only the numbers ['1','2','3']. I've tried a few methods of recursion, however, I can't get it to work correctly due to my other complication, which is adding a separator of "|" in between each 2 digits. So the list would be like so:

11|11|11
11|11|12
11|11|13
11|11|21
11|11|22
11|11|23

etc.. Would be appreciated if someone could point me in the right direction. Also a way of dumping each of the combinations into my MySQL database would be great.

</div>
  • 写回答

2条回答 默认 最新

  • doudeng2025 2013-03-29 17:21
    关注

    Here is a much updated answer (originally updated from this answer]1) to your question:

    function findPermutations($arr, $arrLen, $size, $perArr = array(), $pos = 0, &$found = array()) {
       if ($size==$pos) { //if $pos reach $size then we have found one permutation
          $found[] = vsprintf("%s%s|%s%s|%s%s", $perArr);
          return;
       }
       for ($i=0; $i<$arrLen; $i++) {
    
          $perArr[$pos] = $arr[$i]; //put i'th char in current position
          //The recursive call that move to next position with $pos+1
          findPermutations($arr, $arrLen, $size, $perArr, $pos+1, $found); 
       }
       return $found;
    }
    
    $permutations = array();
    $letters = array('1','2','3');
    $max_length = 6;
    
    $permutations = findPermutations($letters, count($letters), $max_length);
    
    for($i = 0; $i < count($permutations); $i++) {
        print ($permutations[$i].'<br/>');
    }
    

    Here is what I'm doing. I'm passing in an empty array called $permutations by reference, and as I find new permutations, I'm appending them to it. When the function findPermutations() is complete, I end up with an array of all permutation, that I can iterate over or insert. To get the formatting I'm using vsprintf, that lets me pass an array of data and apply a format (in this case %s%s|%s%s|%s%s). Lastly I'm using default argument values to make calling this function cleaner.

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?