2014-02-22 30 views
2

我需要生成一個字符串的所有可能的組合,使用多線程在N個線程之間平均分配工作。因此字符串cat將輸出:生成字符串與多線程的所有組合

c, a, t, ca, ct, ac, at, ta, tc, cat, cta, tac, tca, act, atc 

每個線程包含startIndexendIndex並執行字符串的不同處理。現在,我可以生成一個字符串的所有排列,但我完全無法理解我需要做什麼來修改它以獲取所有組合。任何幫助將不勝感激。

這就是我現在所擁有的:

public void run() { 
    for(int i = startIndex; (i < endIndex); i++) { 
     swap(word, 0, i); // Swap character to zero location. 
     permuteAndCheck(word, 1); // Recursively check permutations 
     swap(word, 0, i); // Undo swap 
    } 
} 

private void permuteAndCheck(char[] word, int start) { 
    if (start < word.length) { 
     // Not yet at the deepest recursion level to compare permutations. 
     for(int i = start; (i < word.length); i++) { 
      swap(word, start, i); 
      permuteAndCheck(word, start + 1); 
      swap(word, start, i); // Restore entry back from previous swap 
     } 
     return; 
    } 

    System.out.print(word + ", "); 
} 

private static final void swap(char[] word, int index1, int index2) { 
    char temp = word[index1]; 
    word[index1] = word[index2]; 
    word[index2] = temp; 
} 
+1

不要忘記tca,atc和cta。 –

+0

..除非命令沒有關係,在這種情況下,你應該忘記那些。 但由於ac和ca都列出了... – keshlam

+0

我沒有列出他們3。抱歉。 – arazzy

回答

0

如果您正在尋找所有組合(即發電機組字符),那麼你已經知道有2-1K-可能性,k是字符數。 (2^k)/ N th組合,第二個線程處理1+(2^k)/ N th到2 *(2^k)/ N th組合等等。

要獲得第j個字符串,請查看j的二進制表示形式,並獲取相應數字爲'1'的字符。即「貓」的第五(二進制:101)組合是c_t。