2011-02-01 65 views
0

我需要取一串單詞,可以是任意數量的單詞並創建從第一個單詞到最後一個單詞的所有可能組合的數組。解析出單詞的所有組合

例如輸入:(輸入可以是詞語的任何量,所述分隔符是一個空間

「WORD1 WORD2 WORD3」

輸出:

1: word1 
2: word1 word2 
3: word1 word2 word3 
4: word2 
5: word2 word3 
6: word3 

任何語言是好的,但更喜歡c#

+1

你錯過了「字詞1 WORD3單詞2」和故意一些人組合?編輯:即你是否指數學意義上的組合(也就是說,不是置換)? – BiAiB 2011-02-01 16:16:19

+0

「word1 word3」按順序排列但缺失 – smci 2015-01-04 18:10:44

回答

0

聽起來像是一個功課題

使用string.split,然後使用兩個for循環。

var wordlist = "word1 word2 word3"; 
var words = wordlist.Split(' '); 
var wordList = new List<string>(); 
for(var i=0; i<words.Length; i++) 
{ 
    var currentWord = words[i]; 
    wordList.add(currentWord); 
    for(var j=i+1; j<words.Length; j++) 
    { 
    currentWord += " " + words[j]; 
    wordList.Add(currentWord); 
    } 
} 

,如果你想成爲梅爾文並獲得額外的分數也可以使用的String.Format或一個StringBuilder ...

0

一個簡單的方法是

  1. 計數從1(1<<w)-1包容性其中w是單詞的數量。
  2. 對於計數器的每個值,考慮值的各個位,如果設置了第n位,則考慮第n個字,否則跳過它。
1

哈斯克爾,只是因爲它的美麗(與C-家庭至少)你說任何語言:

combinations []  = [[]] 
combinations (x:xs) = (combinations xs) ++ map (x:) (combinations xs) 

可以調用這樣的:

combinations ["word1", "word2", "word3"] 

或類似這個,如果你真的必須通過一個空格分隔的字符串:

combinations (words "word1 word2 word3") 
0

Haskell的解決方案轉換爲C#:

public static IEnumerable<IEnumerable<string>> Combinations(IEnumerable<string> words) { 
    if (words.Count() == 0) { 
    return new string[][] { new string[0] }; 
    } else { 
    var x = words.First(); 
    var xs = words.Skip(1); 
    var combinations = Combinations(xs); 
    return combinations.Concat(combinations.Select(s => new string[] { x }.Concat(s))); 
    } 
} 

和字符串的解析之一:

public static IEnumerable<IEnumerable<string>> Combinations(string str) { 
    return Combinations(str.Split(" ")); 
}