2016-04-25 50 views
0

我正在尋找一種PHP中的算法來輸出點的所有可能性。產生我們可以放在任何地方的詞,但現在允許彼此重複兩個點。例如, 「注意」 輸出象下面這樣:在具有所有可能性的字符之間生成點

note 
n.ote 
n.o.te 
n.o.t.e 
no.t.e 
not.e 
n.ot.e 
.... 

,也低於輸出是錯誤的:

n..ote (repeat dots right after each other) 
.note (put dots at first of word) 
note. (put dots at end of word) 
+0

是否有一個最大的努每個名字有多少點? –

+0

不,我需要所有的可能性作爲輸出,但必須驗證兩個點不相互位於一起 – user3221719

+1

因此,最大點將像字符串的長度 - 1.這是一條線索。 :) –

回答

2

遞歸的方式:

Put current char of source in the result string 
if current char is the last one 
    output result 
else 
    call recursive function with the next char index 
    add dot to result and call recursive function with the next char index 

迭代的方式:

2^(Len-1)帶點的組合,Len i字長。 做一個循環k = 0..2^(Len-1) - 1並在那些地方,其中k的二進制表示包含每k插入點1 S(K = 2 =二進制010 =>po.le

0

我找到了解決辦法,最終通過的https://stackoverflow.com/users/844416/mbo有益的指導:

function stringInsert($str,$insertstr,$pos){ 
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos); 
    return $str; 
} 

function generate($var="note",$i=0){ 
    $length = strlen($var); 

    while ($i+1 < $length) { 
     $i++; 
     $new = stringInsert($var,'.',$i); 
     echo $new; 
     generate($new,$i+1); 

    } 
} 


generate('shaghayegh'); 

例如關鍵字 「筆記」 產生7串

關鍵字 「shaghayegh」 產生511串