【发布时间】:2016-03-30 12:52:22
【问题描述】:
对于我的问题,我有一个大于 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) { throw new ArgumentException("值不能为空。", "fullSet"); } 否则,如果(子集大小
// 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;
}
【问题讨论】:
-
那么您想从
n值生成k值的所有组合吗?喜欢n在统计中选择k或nCk? -
我想要来自“n”个值的“k”个对象的每个唯一组合,其中长度 n 是可变的,其中 k 长度始终是 6。
标签: c# list combinations