-5

How to permute a tuple containing several string items?

2 Answers2

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#

Community
  • 1
  • 1
DrKoch
  • 9,556
  • 2
  • 34
  • 43
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