如何通过组合获得输出字符串数组的所有可能性?

时间:2016-07-29 08:47:34

标签: c# combinations

我需要任何String List输出所有可能性。像那样。    这让我得到了720个不同的字符串。

List<String> items = new List<String>();
        items.AddRange(new String[] { "a", "b", "c", "d", "e", "f" });
  

输出;

     

1-)a b c d e f

     

2-)a b c d f e

     

3-)a b c e d f

     

4-)a b c e f d

     

5-)a b c f d e

     

6-)a b c f e d

     

7-)a b d c e f

     

8-)a b d c f e

     

9-)a b d e c f

     

10-)a b d e f c

     

11-)...........

     

12-)...........

     

13-)b a c d e f

     

720 - )..........

1 个答案:

答案 0 :(得分:2)

你走了:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main()
        {
            List<String> items = new List<String>();
            items.AddRange(new String[] { "a", "b", "c", "d", "e", "f" });

            int i = 0;

            foreach (var permutation in Permute(items))
                Console.WriteLine(++i + ": " + string.Join(" ", permutation));
        }

        public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> seq)
        {
            return
                from item in seq.Select((value, index) => new {value, index})
                from remainder in seq.Count() == 1 ? new[]{new T[0]} : Permute(allExcept(seq, item.index))
                select new[]{item.value}.Concat(remainder);
        }

        static IEnumerable<T> allExcept<T>(IEnumerable<T> seq, int indexToSkip)
        {
            return 
                from item in seq.Select((value, index) => new {value, index})
                where item.index != indexToSkip 
                select item.value;
        }
    }
}

如果输入中有重复的字符串,并且您想要消除输出中的重复排列,请使用DistinctBy()originally written by Jon Skeet),如下所示:

var uniquePerms = Permute(items).DistinctBy(p => string.Join(" ", p));

其中DistinctBy()IEnumerable<T>的扩展方法:

public static class EnumerableExt
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        return source.DistinctBy(keySelector, null);
    }

    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IEqualityComparer<TKey> comparer)
    {
        return distinctByImpl(source, keySelector, comparer);
    }

    static IEnumerable<TSource> distinctByImpl<TSource, TKey>(
        IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector,
        IEqualityComparer<TKey> comparer)
    {
        var knownKeys = new HashSet<TKey>(comparer);
        return source.Where(element => knownKeys.Add(keySelector(element)));
    }
}