PHP列出所有可能的具有特定数字的6位数字

时间:2013-03-29 17:08:50

标签: php loops recursion permutation combinations

如何生成给定数量的数字并使用特定数字的所有可能数字?

所以基本上,我希望有一个6位数字,例如只使用数字['1','2','3']。我已经尝试了一些递归方法,但是,由于我的其他复杂功能,我无法让它正常工作,即添加“|”的分隔符在每两个数字之间。所以列表就是这样:

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

等。 如果有人能指出我正确的方向,将不胜感激。 另外一种将每个组合转储到我的MySQL数据库中的方法都很棒。

2 个答案:

答案 0 :(得分:1)

这是一个更新的答案(最初从此答案更新1)到您的问题:

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/>');
}

这就是我正在做的事情。我通过引用传入一个名为$permutations的空数组,当我找到新的排列时,我将它们附加到它上面。当函数findPermutations()完成时,我最终会得到一个包含所有排列的数组,我可以迭代或插入。要获取我正在使用vsprintf的格式,我可以传递数据数组并应用格式(在本例中为%s%s|%s%s|%s%s)。最后,我使用默认参数值来调用此函数更清晰。

答案 1 :(得分:0)

你的意思是这样的吗?

$letters='123'; // add other numbers

for($i=0;$i<3;$i++) { //generate 3 pairs
  $pairs[]=$letters[rand(0,2)] . $letters[rand(0,2)];
}
//then join them together
$finalstring=implode('-',$pairs);
相关问题