日期:2014-05-17  浏览次数:20880 次

使用枚举器求索引的全排列
caozhy使用枚举器求索引的全排列是个好办法,学习了一下,重新写了一个函数。

/// <summary>
  /// 使用枚举器生成[n, count)索引全排列 。
  /// </summary>
  /// <param name="count">数目,索引在[0, count - 1]间 。</param>
  /// <returns>索引全排列 。</returns>
  /// <exception cref="ArgumentOutOfRangeException">如果count非法,抛出ArgumentOutOfRangeException 。</exception>
  public static IEnumerable<IList<int>> PermutationIndice(int count)
  {
  if (count < 0)
  {
  throw new ArgumentOutOfRangeException("count");
  }

  IEnumerable<int> allIndice = Enumerable.Range(0, count);
  IEnumerable<IList<int>> permutation = null;
  for (int i = 0; i < count; i++)
  { // 每次迭代,求i个索引的排列全集
  if (i == 0)
  {
  permutation = Enumerable.Select<int, IList<int>>(allIndice, x => new int[] { x });
  //permutation = allIndice.Select<IList<int>>(x => new int[] { x });
  }
  else
  {
  permutation = Enumerable.SelectMany<IList<int>, IList<int>>(permutation,
  l => Enumerable.Select<int, IList<int>>(allIndice.Except(l), x => new List<int>(l).Concat(new int[] { x }).ToList()));
  //l => allIndice.Except(l).SelectMany<IList<int>>(x => new List<int>(new List<int>(l).Concat(new int[] { x}).ToList())));
  }
  }

  return permutation;
  }

------解决方案--------------------
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = Arrange(4);
            foreach (var item in result)
            {
                Console.WriteLine(string.Join(",", item.Select(x => x.ToString()).ToArray()));
            }
        }

        static IEnumerable<IEnumerable<int>> Arrange(int n)
        {
            IEnumerable<IEnumerable<int>> result = Enumerable.Range(0, n).Select(x => new List<int>() { x });
            while (result.First().Count() < n)
            {
                result = result.SelectMany(x => Enumerable.Range(0, n).Except(x).Select(y => x.Concat(new List<int>() { y })));
            }
            return result;
        }
    }
}