2013-03-29 101 views
0

如何生成给定数量的数字和使用特定数字的每个可能数字?所以基本上,我想有一个6位数的数字,例如只使用数字['1','2','3']。我已经尝试了递归的一些方法,但是,由于我的其他并发症,我添加了“|”分隔符,我无法正确工作。在每两位数之间。因此,该列表会像这样:如果有人能在正确的方向指向我PHP列出所有可能的具有特定数字的6位数字

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

等。 将不胜感激。 也是一种将每种组合转储到我的MySQL数据库的方法。

+0

http://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers –

+0

忘记分隔符,你可以随时添加它们。只需要选择一个随机数(1到3之间)6次,并将它们连接在一起。检查你的数据库表,看看它是否存在,如果没有添加它。运行它一堆。最终你会得到他们。 –

+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)。最后,我使用默认参数值来调用这个函数更清晰。

+0

你可以在这里测试这个:http://phpcodepad.com/ –

+0

谢谢你,这是完美的。但是 - 请问如何将每个2位数与“|”分开?对不起,我是PHP新手。 – Engine

+0

'return'语句上方的行用于打印每个排列,您可以将它们更改为'print $ perArr [0]。$ perArr [1]。'|'。$ perArr [2]。$ perArr [ 3]。'|'。$ perArr [4]。$ perArr [5]'或者你可以在其中添加你的MySQL INSERT命令(如果你这样做,我会将它重命名为storePermutation) –

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); 
相关问题