如何置换C#元组项?

时间:2015-07-04 13:57:01

标签: c# tuples permutation combinatorics

如何置换包含多个字符串项的元组?

2 个答案:

答案 0 :(得分:2)

因为"6"是一个非常小的数字,所以将其写下来是最有效的:

tupple1 = a,b,c
tupple2 = a,c,b
...

您无法在更短的时间内创建程序。

如果您对更通用的解决方案感兴趣,请参阅SO上的大量链接之一,例如:Permutation algorithms in C#

答案 1 :(得分:0)

使用Tuple,我很害怕。所以:

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

使用修改后的Eric Liperts扩展方法,您可以执行以下操作:

扩展方法:

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

使用案例:

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

如果您希望获得所有排列,包括“aaa”“aab”等,只需删除

来自扩展方法的

where !accseq.Contains(item)