How to permute a tuple containing several string items?
Asked
Active
Viewed 274 times
-5
-
The question is about if it's possible at all (having n-item tuple) – Andrejs Igumenovs Jul 04 '15 at 14:38
2 Answers
2
Because "6"
is a very small number, it is most efficient to just write it down:
tupple1 = a,b,c
tupple2 = a,c,b
...
You can't create a program in shorter time.
If you are interested in a more genral solution however, see one of the plenty links on SO, example : Permutation algorithms in C#
-
Well, if I have one more `string d`, then the number would be 24. – Andrejs Igumenovs Jul 04 '15 at 14:12
-
1
-
-
@AndrejsIgumenovs, if you want help creating the `n!` permutations for an `n` element tuple, then please post a question asking for that and showing what you have achieved so far. As it stands, this is a good answer to your current bad question. – David Arno Jul 04 '15 at 14:29
-
Please check the links in the right column "Related". You'll find plenty answers – DrKoch Jul 04 '15 at 14:30
0
Using Tuple
, manually I'm afraid. So:
var tuple = new Tuple<string, string, string>("a", "b", "c");
var combination_1 = String.Concat(tuple.Item1, tuple.Item2, tuple.Item3);
var combination_2 = String.Concat(tuple.Item1, tuple.Item3, tuple.Item2);
var combination_3 = String.Concat(tuple.Item2, tuple.Item1, tuple.Item3);
var combination_4 = String.Concat(tuple.Item2, tuple.Item3, tuple.Item1);
var combination_5 = String.Concat(tuple.Item3, tuple.Item1, tuple.Item2);
var combination_6 = String.Concat(tuple.Item3, tuple.Item2, tuple.Item1);
Using modified Eric Liperts extension method, you could do something like this:
Extension method:
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate
( emptyProduct, (accumulator, sequence) =>
from accseq in accumulator
from item in sequence
where !accseq.Contains(item)
select accseq.Concat(new[] { item })
);
}
Use case:
var array = new string[] { "a", "b", "c", "d", "e" };
var result = Enumerable.Range(0, array.Length).Select(_ => array).CartesianProduct();
// Print results
foreach (var item in result)
Console.WriteLine(String.Join("", item));
If you ever wish to get all permutations including "aaa", "aab" etc. simply remove
where !accseq.Contains(item)
from extension method.

msmolcic
- 6,407
- 8
- 32
- 56
-
Also this way: `string[] stringArray = {tuple.Item1, tuple.Item2, ... tuple.ItemN};` (unpacking tuple object first) – Andrejs Igumenovs Jul 04 '15 at 14:54
-
@AndrejsIgumenovs yeah, that's right. You could get items out of tuple into array and use the same extension method. – msmolcic Jul 04 '15 at 14:55