絕對的頭腦在這個空白。這是那些日子之一。但是我一直在尋找一種解決方案來獲得一定長度的項目列表的獨特組合。例如給出一個列表[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;
}
}
該做的事情是應該做的,但它返回所有排列,無論他們是唯一的。我試圖讓我的腦袋圍繞這段代碼的哪一部分(如果有的話)進行更改以獲取唯一值。或者是實現此功能的更好方法?
列表中的項目是否唯一?即你能列出一個清單[a,a,b,c]嗎? –
術語:您要查找的內容稱爲「組合」,這意味着您可以進行不同的無序選擇,其中排列是不同的有序選擇。 –