2010-12-14 54 views
4

可能重複:
Generate list of all possible permutations of a string創建可能的字符串組合的名單

傢伙嗨,

我需要在一個小的算法項目中,我需要能夠正常工作根據給定的限制列出並寫入文本文件給定字符集合的可能組合。

例如,如果我輸入字符「a」,「b」和「c」和將限制設置爲3的可能的輸出將是:

a 
b 
c 
aa 
bb 
cc 
ab 
ac 
ba 
bc 
ca 
cb 
... 
    aaa 
    bbb 
    ccc 
    ... 
    ... 
    abc 
    acb 
    bac 
    bca 
    cab 
    cba 

直到所有可能的組合已經被設計。

將此文字寫入文本文件對我來說沒有問題。有一個可以編寫組合的算法是我不擅長的。

欣賞.NET(C#或VB)代碼。

感謝。

PS

在一個側面說明,我不知道它要花多長時間才能爲應用程序創建的所有可能的鍵盤字符的字符串組合以及有多大的文件會得到如此。

更新時間: 我也應該表現出從n個字符的限制隱含字符組合..

+0

快速谷歌搜索「字符組合算法」發現了這個討論(這是在其他好看的候選人名單先打),他們勾勒出的算法:http://www.daniweb.com/論壇/ thread110604.html – FrustratedWithFormsDesigner 2010-12-14 20:14:20

+0

有'n ** b'獨特的'n'項目從一組大小'b'排列。 (特別是,這告訴你基數b中有多少個數字可以表示(例如5位:'2 ** 5 == 32'))。即使假設ASCII(95個可打印字符),也有857,375個3個字母,81,450,625個4個字母(如此類推)的字符串。這種增長顯着。而nowadaws,你有256個字符甚至Unicode的代碼頁。對於許多目的,有更便宜的解決方案... – delnan 2010-12-14 20:18:34

回答

1

您可以使用遞歸實現枚舉字符串中的所有排列。一個快速但實用的實現可能如下所示:

編輯:您將OP更改爲包含長度小於輸入字符集的字符串。以下代碼已被修改。它給出了你的問題中的輸出。

static void BuildPermutations(string input, char[] current, int index, int depth, List<string> perms) 
{ 
    if (index == depth) 
    { 
     perms.Add(new string(current, 0, depth)); 
     return; 
    } 
    for (int n = 0; n < input.Length; ++n) 
    { 
     current[index] = input[n]; 
     BuildPermutations(input, current, index + 1, depth, perms); 
    } 
} 


static void Main(string[] args) 
{ 
    string input = "abc"; 
    char[] current = new char[input.Length]; 
    List<string> perms = new List<string>(); 
    for (int n = 1; n <= 3; ++n) 
     BuildPermutations(input, current, 0, n, perms); 
    foreach (string s in perms) 
     System.Console.WriteLine(s.ToString()); 
} 
1

嗯,你的榜樣,我可能會嘗試這樣的事情。

string chars = "abc"; 

for (int a = 0; a < chars.Length; a++) 
{ 
    for (int b = 0; b < chars.Length; b++) 
    { 
     for (int c = 0; c < chars.Length; c++) 
     { 
      string row = String.Format("{0}{1}{2}", chars[a], chars[b], chars[c]); 
     } 
    } 
} 

這只是在這裏輸入,所以它可能包含錯誤。另外,我不確定字符數限制是否與可能的字符數相關聯。但也許這會給你一個出發點。