对此绝对头脑一片空白。这是那些日子之一。但我一直在寻找一种解决方案,以获取特定长度的项目列表的独特组合。例如,给定一个列表 [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;
}
}
这做了它应该做的,但它返回所有排列,不管它们是否唯一。我试图了解要更改此代码的哪一部分(如果有的话)以获得唯一值。还是实现此功能的更好方法?
最佳答案
试试这个:
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
这是您期望的吗?
关于c# - 列表的唯一组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12249051/