对于我的问题,我有一个大于6+的计数列表。从该列表中我想制作一个列表,其中包含正好6张卡长的原始卡片的所有可能组合。 (它们必须是唯一的,订单并不重要)
所以对象 01,02,03,04,05,06 和我一样 06,05,04,03,02,01
//STARTER list with more then 6 value's
List < ClassicCard > lowCardsToRemove = FrenchTarotUtil.checkCountLowCardForDiscardChien(handCards);
我找到并使用的解决方案:
public static List generateAllSubsetCombinations(object [] fullSet,ulong subsetSize){ if(fullSet == null){ 抛出新的ArgumentException(&#34; Value不能为null。&#34;,&#34; fullSet&#34;); } else if(subsetSize&lt; 1){ 抛出新的ArgumentException(&#34;子集大小必须为1或更大。&#34;,&#34; subsetSize&#34;); } else if((ulong)fullSet.LongLength&lt; subsetSize){ 抛出新的ArgumentException(&#34;子集大小不能大于整个集合中的条目总数。&#34;,&#34; subsetSize&#34;); }
// All possible subsets will be stored here
List<object[]> allSubsets = new List<object[]>();
// Initialize current pick; will always be the leftmost consecutive x where x is subset size
ulong[] currentPick = new ulong[subsetSize];
for (ulong i = 0; i < subsetSize; i++) {
currentPick[i] = i;
}
while (true) {
// Add this subset's values to list of all subsets based on current pick
object[] subset = new object[subsetSize];
for (ulong i = 0; i < subsetSize; i++) {
subset[i] = fullSet[currentPick[i]];
}
allSubsets.Add(subset);
if (currentPick[0] + subsetSize >= (ulong)fullSet.LongLength) {
// Last pick must have been the final 3; end of subset generation
break;
}
// Update current pick for next subset
ulong shiftAfter = (ulong)currentPick.LongLength - 1;
bool loop;
do {
loop = false;
// Move current picker right
currentPick[shiftAfter]++;
// If we've gotten to the end of the full set, move left one picker
if (currentPick[shiftAfter] > (ulong)fullSet.LongLength - (subsetSize - shiftAfter)) {
if (shiftAfter > 0) {
shiftAfter--;
loop = true;
}
}
else {
// Update pickers to be consecutive
for (ulong i = shiftAfter+1; i < (ulong)currentPick.LongLength; i++) {
currentPick[i] = currentPick[i-1] + 1;
}
}
} while (loop);
}
return allSubsets;
}
答案 0 :(得分:0)
这个不是来自我,但它确实起作用了!
List <ClassicCard> lowCardsToRemove = FrenchTarotUtil.checkCountLowCardForDiscardChien(handCards);
var result = Combinator.Combinations(lowCardsToRemove, 6);
public static class Combinator
{
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
}
}