所有可能的三到六个不同字符串的排列

时间:2011-06-23 15:51:02

标签: arrays algorithm vb6 permutation

所有的一切,我一直在墙上撞墙两天。我有googledgoogled,我似乎无法找到解决方案。这就是我所拥有的:

我有两到六个不同的字符串数组(取决于用户的选择)但是对于这个问题,我们假设有3个单独的字符串数组:

  • Array1 - Tom,Dick,Harry
  • Array2 - 吃,做饭,喝酒
  • Array3 - 汤,苏打水,沙拉

我希望生成的数组包含这三个字符串数组的所有可能组合,但我不想组合同一列表中包含的值(否:Tom Dick Harry)。这就是我要看的结果数组:


  1. Tom Eats Soup
  2. Tom Eats Soda
  3. Tom Eats Salad
  4. Dick Eats Soup
  5. Dick Eats Soda
  6. Dick Eats Salad
  7. Harry Eats Soup
  8. Harry Eats Soda
  9. Harry Eats Salad

  10. 我正在寻找一个VB6解决方案,但我很欣赏大多数其他编程语言中的解决方案或算法。

    提前感谢您的有用建议。

1 个答案:

答案 0 :(得分:5)

如果这就是你要做的全部,那就做一个三重嵌套for循环:

for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
         for(int k = 0; k < 3; k++) {
             output array1[i] + " " array2[j] + " " + array3[k]; 
         }  
    }
}

您可以翻译为VB6。像C#和VB.NET这样的现代语言可以让你更精彩地表达它:

string[] names = new[] { "Tom", "Dick", "Harry" };
string[] verbs = new[] { "Eats", "Cooks", "Drinks" };
string[] foods = new[] { "Soup", "Soda", "Salad" };

var combinations = from name in names
                   from verb in verbs
                   from food in foods
                   select String.Join(" ", new[] { name, verb, food });

foreach(var combination in combinations) {
    Console.WriteLine(combination);
}