2014-10-08 311 views
0

我有这些数据C#递归循环

string [] letters = {"a","b","c"}; 

我想要的功能等,generateString(1) 如果值为1,则输出为:

a 
b 
c 

如果generateString(3),输出

a 
b 
c 
aa 
ab 
ac 
ba 
bb 
bc 
ca 
cb 
cc 
aaa 
aab 
aac 
aba 
abb 
abc 
aca and so on... 

我可以像这样做,

foreach(var a in data){ 
foreach(var b in data){ 
    foreach(var c in data){ 
    Console.WriteLine(a + b + c); 
    } 
} 
} 

它只能生成高达3,如果我想使它4,然后我添加另一个foreach,这是我认为不是一个更好的主意。

有什么建议吗?

+1

如果你做了递归,它会是什么样子?你尝试过什么吗? – 2014-10-08 10:22:25

+0

在尝试之前,您可能会尝试研究递归是什么。请求其他人为您尝试。 – 2014-10-08 10:24:55

回答

0
static string[] generateString(string[] letters, int len) 
{ 
    if (len < 0) throw new ArgumentOutOfRangeException("length can't be less than zero."); 
    switch (len) 
    { 
     case 0: return new string[0]; 
     case 1: return letters; 
     default: 
      // all possible combinations which are shorter than required 
      // recursion is used here 
      var shorter_x = generateString(letters, len - 1).ToArray(); 

      // all combinations which have length = len - 1 
      var shorter_1 = shorter_x.Where(line => line.Length == len - 1).ToArray(); 

      // resulting array 
      return shorter_x.Union(letters.SelectMany(letter => shorter_1.Select(shorter => letter + shorter))).ToArray(); 
    } 
} 

UPD:代表数据

char[] letters = { 'a', 'b', 'c' } 

会更一致。在这种情况下,函数看起来像

static string[] generateString(char[] letters, int len) 
{ 
    if (len < 0) throw new ArgumentOutOfRangeException("length can't be less than zero."); 
    switch (len) 
    { 
     case 0: return new string[0]; 
     case 1: return letters.Select(char.ToString).ToArray(); 
     default: 
      ...... 
+0

它确实有效!但我想要使用已生成的每一个字符串。如果我要使用generateString(20),我的电脑就会崩溃,因为它无法处理存储到一个变量的大数据。 – user3898263 2014-10-08 11:45:01

+0

您可以尝试使用非递归版本。和懒惰的迭代器 – talex 2014-10-08 14:37:57

0

它看起来像成才这样

List<List<String>> foo(int i){ 
    if(i==1){ 
     return new List<List<String>>(new List<String>("a", "b", "c")); 
    } else{ 
     var result = new List<List<String>>(); 
     foreach(List<String> list in foo(i-1)){ 
      foreach(String elem in new String[]{"a", "b", "c"}){ 
       var tmp = new List<String>(list); 
       tmp.Add(elem); 
       result.Add(tmp); 
      } 
     } 
     return result; 
    } 
} 

我不知道sintax和列表构造函数,但在总体思路所示