开发者

All Possible permutations of three to six different strings

All, I have been beating my head against the wall for two days on this one. I have googled and googled and I can't seem to find a solution. Here is what I have:

I have from two to six different string arrays (depending upon a user's selection) but for this qu开发者_高级运维estion lets assume 3 separate string arrays:

  • Array1 - Tom, Dick, Harry
  • Array2 - Eats, Cooks, Drinks
  • Array3 - Soup, Soda, Salad

I want the resulting Array to contain all possible combinations of these three string arrays but I don't want to combine the values contained in the same list (no: Tom Dick Harry). This is how I was the resulting array to look:


  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

I'm looking for a VB6 solution but I would appreciate a solution or Algorithm in most any other programming language.

Thank you in advance for your helpful suggestions.


If this is all you have to do, just do a triple-nested for loop:

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]; 
         }  
    }
}

You can translate to VB6. Modern languages like C# and VB.NET will let you express this more beautifully:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜