【问题标题】:Unique combinations of list列表的独特组合
【发布时间】:2012-09-03 13:41:42
【问题描述】:

对此绝对头脑空白。这是那些日子之一。但我一直在寻找一种解决方案来获得一定长度的项目列表的独特组合。例如,给定一个列表 [a, b, c] 和长度为 2,它将返回 [a,b] [a,c] [b,c] 但不返回 [b,a] [c,a] [c ,b]

为此,我找到了许多代码,但似乎没有一个适合。以下代码似乎最合适,我一直在尝试根据需要对其进行更改:

// Returns an enumeration of enumerators, one for each permutation
// of the input.
public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> list, int count)
{
    if (count == 0)
    {
        yield return new T[0];
    }
    else
    {
        int startingElementIndex = 0;
        foreach (T startingElement in list)
        {
            IEnumerable<T> remainingItems = AllExcept(list, startingElementIndex);

            foreach (IEnumerable<T> permutationOfRemainder in Permute(remainingItems, count - 1))
            {
                yield return Concat<T>(
                    new T[] { startingElement },
                    permutationOfRemainder);
            }
            startingElementIndex += 1;
        }
    }
}

// Enumerates over contents of both lists.
public static IEnumerable<T> Concat<T>(IEnumerable<T> a, IEnumerable<T> b)
{
    foreach (T item in a) { yield return item; }
    foreach (T item in b) { yield return item; }
}

// Enumerates over all items in the input, skipping over the item
// with the specified offset.
public static IEnumerable<T> AllExcept<T>(IEnumerable<T> input, int indexToSkip)
{
    int index = 0;
    foreach (T item in input)
    {
        if (index != indexToSkip) yield return item;
        index += 1;
    }
}

这完成了它应该做的事情,但它返回所有排列,不管它们是唯一的。我试图弄清楚这段代码的哪一部分(如果有的话)要更改以获得唯一值。或者是实现此功能的更好方法?

【问题讨论】:

  • 列表中的项目是否唯一? IE。你能有一个列表 [a, a, b, c] 吗?
  • 术语:您要查找的内容称为“组合”,这意味着您可以进行不同的无序选择,其中排列是不同的有序选择。

标签: c# algorithm


【解决方案1】:

试试这个:

void Main()
{
    var list = new List<string> { "a", "b", "c", "d", "e" };
    var result = GetPermutations(list, 3);
}

IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int count)
{
    int i = 0;
    foreach(var item in items)
    {
        if(count == 1)
            yield return new T[] { item };
        else
        {
            foreach(var result in GetPermutations(items.Skip(i + 1), count - 1))
                yield return new T[] { item }.Concat(result);
        }

        ++i;
    }
}

如果计数为 2,则返回:

a, b
a, c
a, d
a, e
b, c
b, d
b, e
c, d
c, e
d, e

如果计数为 3,则返回:

a, b, c
a, b, d
a, b, e
a, c, d
a, c, e
a, d, e
b, c, d
b, c, e
b, d, e 
c, d, e

这是你所期望的吗?

【讨论】:

  • 我希望我能在一小时前找到这个答案!
  • 对于寻找所有组合的任何人 - b, a 以及 a, b - 将 else 中的行更改为 GetPermutations(items.Except(new[] { item }), count - 1))
【解决方案2】:

实现中的剩余项目列表包含除当前起始项目之外的所有项目。

获取起始项目之后的项目:

IEnumerable<T> remainingItems = list.Skip(startingElementIndex + 1);

【讨论】:

  • 这是对我有用的。我知道我必须避免列表中较早的项目,但无法弄清楚如何。 Linq 对我来说是新的,所以不知道这个功能。非常感谢。
【解决方案3】:

您应该使用仅提供您正在考虑的项目之后的项目的子序列,而不是 AllExcept。

【讨论】:

    【解决方案4】:

    在 set-speak 中,您要查找的是基于长度 n 的幂集的子集。如果您在 Google 上搜索“C#”+“Power set”,那么您应该可以开始使用。

    http://en.wikipedia.org/wiki/Power_set

    【讨论】:

      【解决方案5】:

      并且只是为了完整性..如果您已经拥有所有排列 ( :) 因为它对我来说只是一个复制和粘贴) 使用下面的扩展方法,您可以获得如下不同的结果:

      var result = permutations.Distinct((p1, p2) => !p1.Differs(p2));
      

      只是一个例子,如果您经常使用比较列表,其他方法也可能在其他地方派上用场

      public static class Extensionmethods
      {
          /// <summary>
          /// Checks if both IEnumerables contain the same values regardless of their sequence
          /// </summary>
          /// <typeparam name="T">Type of Elements</typeparam>
          /// <param name="result">IEnumerable to compare to</param>
          /// <param name="compare">IEnumerable to compare to</param>
          /// <returns>Returns false if both IEnumerables contain the same values</returns>
          public static bool Differs<T>(this IEnumerable<T> result, IEnumerable<T> compare)
          {
              if (result == null && compare == null)
                  return false;
              if (result != null && compare == null)
                  return true;
              if (result == null && compare != null)
                  return true;
              return result.Count() != compare.Count()
                  || compare.Where(c => c == null).Count() != result.Where(r => r == null).Count()
                  || compare.Where(c => c != null).Distinct().Any(item => result.Where(r => item.Equals(r)).Count() != compare.Where(r => item.Equals(r)).Count());
          }
          /// <summary>
          /// Checks if both IEnumerables contain the same values (corresponding to <paramref name="comparer"/> regardless of their sequence
          /// </summary>
          /// <typeparam name="T">Type of Elements</typeparam>
          /// <param name="result">IEnumerable to compare to</param>
          /// <param name="compare">IEnumerable to compare to</param>
          /// <param name="comparer">IEqualityComparer to use</param>
          /// <returns>Returns false if both IEnumerables contain the same values</returns>
          public static bool Differs<T>(this IEnumerable<T> result, IEnumerable<T> compare, IEqualityComparer<T> comparer)
          {
              if (result == null && compare == null)
                  return false;
              if (result != null && compare == null)
                  return true;
              if (result == null && compare != null)
                  return true;
              return result.Count() != compare.Count()
                  || compare.Where(c => c == null).Count() != result.Where(r => r == null).Count()
                  || compare.Where(c => c != null).Distinct().Any(item => result.Where(r => comparer.Equals(item, r)).Count() != compare.Where(r => comparer.Equals(item, r)).Count());
          }
      
          public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source, Func<T, T, bool> compareFunction, Func<T, int> hashFunction = null)
          {
              var ecomparer = new DynamicEqualityComparer<T>(compareFunction, hashFunction);
              return source.Distinct(ecomparer);
          }
      
      
      }
      
      internal class DynamicEqualityComparer<T> : IEqualityComparer<T>
      {
      
          public DynamicEqualityComparer(Func<T, T, bool> equalFunction, Func<T, int> hashFunction = null)
          {
              this.equalFunc = equalFunction;
              this.hashFunc = hashFunction;
          }
      
          private Func<T, T, bool> equalFunc;
          public bool Equals(T x, T y)
          {
              if (x == null && y == null) return true;
              if (x == null) return false;
              if (y == null) return false;
              if (hashFunc != null)
              {
                  if (hashFunc.Invoke(x) != hashFunc.Invoke(y)) return false;
              }
              return this.equalFunc.Invoke(x, y);
          }
      
          private Func<T, int> hashFunc;
          public int GetHashCode(T obj)
          {
              if (hashFunc != null) return hashFunc.Invoke(obj);
              return 0;
          }
      }
      

      【讨论】:

        【解决方案6】:

        我已经尝试了上面的所有方法,但都失败了,因为如果输入较大,它们会吃掉很多 Ram 并且崩溃。但我有一个非常简单的解决方案:

        class Program
        {
            static List<string> textArr = new List<string>() { "1", "2", "3", "4" };
            static void Main(string[] args)
            {
                getCombination();
            }
        
           static void getCombination() {
                var maxCombination = 1;
                List<string> Combinations = new List<string>();
                for (var i = 1; i <= textArr.Count(); i++)
                {
                    maxCombination = maxCombination * i;
                }
        
        
                while (Combinations.Count<maxCombination)
                {
                    var temp = string.Join(" ", textArr.OrderBy(x => Guid.NewGuid()).ToList());
        
                    if (Combinations.Contains(temp))
                    {
                        continue;
                    }
                    else {
                        Combinations.Add(temp);
                    }
        
                }
        
                Combinations.ForEach(x => {
                    Console.WriteLine(x+" ");
                });
        
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2011-07-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多