2016-07-20 39 views
-2

您好我想知道如果我可以創建接受一個句子,並把它變成一個數組,例如數組置換爲了算法,如果有人可以幫助我與循環編碼

$sentence = 'my name is john' 

那麼陣列將是:

$arr = {my name is john, 
my name is, my name john, my is john, name is john, 
my name, my is, my john, name is, name john, is john, 
my, name, is, john} 

有人可以幫助我在任何類型的循環的實現,因爲即時通訊目前創建一個簡單的搜索引擎算法THX將是巨大的:d

+0

你想只需在數組內重複一次這個句子? – Will

+0

yes @ user866762但是在不同的長度tho中,從上面可以看出,第一個循環是整個句子,然後是長度爲1的部分句子,然後是長度爲2的部分句子,直到單個word – Hendry

+1

把它看作是一個n位整數,每一位對應一個單詞是否被包含。循環從1到(1 << n) - 1,在這種情況下是1到15,得到你的15個句子(你只有14個,因爲你錯過了「我的名字約翰」)。 – samgak

回答

1

把它看作一個n位整數,每一位對應於一個單詞是否包含在你的數組中的給定字符串中。循環從1到(1 < < n) - 1,在本例中爲1到15,以獲得您的15個單詞列表,並且爲每個單詞檢查整數中的每個位並添加相應的單詞(如果相應的單詞位設置:

function getCombinations($sentence) 
{ 
    $words = explode(" ", $sentence); 
    $combinations = array(); 
    for($i = 1; $i < (1 << count($words)); $i++) 
    { 
     $wordlist = ""; 
     for($j = 0; $j < count($words); $j++) 
     { 
      if($i & (1 << $j)) 
      { 
       $wordlist = $wordlist . " " . $words[$j]; 
      } 
     } 
     array_push($combinations, substr($wordlist, 1)); 
    } 
    return $combinations; 
} 

$a = "my name is john"; 
print_r(getCombinations($a)); 

如果你想你的字符串由單詞的數量進行排序,添加額外的循環的字數:

for($wordcount = count($words); $wordcount >= 1; $wordcount--) 
{ 
    for($i = 1; $i < (1 << count($words)); $i++) 
    { 
     if(NumberOfSetBits($i) == $wordcount) 
     {    
      $wordlist = ""; 
      // generate word list.. 
     } 
    } 
} 

NumbeOfSetBits function from here

相關問題