我有一个对象列表,这些对象的数量是动态的。我需要找到这些对象的所有可能的组合。查找所有可能的组合,并重新选择允许的项目
我目前在这里我采取的对象列表的阶段,使用下面的代码没有repitition返回所有可能的组合:
static void Main(string[] args)
{
//Say, inputList contains randomObject1,randomObject2 and randomObject3
List<List<RandomObject>> AllCombos = ItemCombinations(inputList);
}
//maxComboCount denotes the maximum number of elements that can be in the combination
public static List<List<T>> ItemCombinations<T>(List<T> inputList, int maxComboCount)
{
int nonEmptyCombinations = (int)Math.Pow(2, inputList.Count) - 1;
List<List<T>> listOfCombinations = new List<List<T>>();
for (int i = 1; i <= nonEmptyCombinations; i++)
{
List<T> thisCombination = new List<T>();
for (int j = 0; j < inputList.Count; j++)
{
if ((i >> j) % 2 != 0)
{
thisCombination.Add(inputList[j]);
}
}
if (thisCombination.Count <= maxComboCount)
{
listOfCombinations.Add(thisCombination);
}
}
return listOfCombinations;
}
我如何获得所有其他组合,在那里重复项目,maxComboCount将永远在那里,否则我所需的场景可能会陷入无限循环(如果我错了,请纠正我)。
例如, InputList:{r1,r2,r3}
当前阶段:{r1},{r2},{r3},{r1,r2},{r2,r3},{r3,r1},{r1,r2 ,r3}
通缉阶段(给定maxComboCount约束= 4):{r1},{r2},{r3},{r1,r1},{r1,r2},{r1,r3},{r2, {r2,r3},{r1,r1,r1},{r1,r1,r2},{r1,r1,r3}等等。 。
有一件事我试过了,
我重复,直到maxBaseCardCount并在每次迭代到另一个tempList加入inputList,我再传给这个tempList为满足在ItemCombinations参数HOD。
//The loop will be constrained by the maximum number of objects allowed
for (int i = 0; i < maxComboCount; i++)
{
tempList.AddRange(inputList);
}
List<List<RandomObject>> AllCombos = ItemCombinations(tempList);
这应该是一个快速和肮脏的解决办法,并确实给我需要的输出(有很多重复的值),但我不是很肯定它多少可以打破之前举行。因此,任何比我的方法更可靠的方法将非常感谢。
编辑
我加入问题的解释,请让我知道是否有任何其他的简化要求
InputList:这是一个对象的列表,从中可以组合成由
ItemCombinations:该函数返回从给定列表中的所有组合,而无需repitition(不是我想要的)
对于inputList = {1,2},ItemCombination返回:空,{1},{2},{1,2},即从长度为n的任何给定的列表中查阅
所有2^N唯一组合,我希望能够将这些项目与允许的重复项以及动态组合的长度结合起来。
实施例:
例如InputList:{r1,r2,r3}
ItemCombination函数最初返回:{r1},{r2},{r3},{r1,r2},{r2,r3},{r3,r1},{r1 ,R2,R3}
现在,我要的是,可以作出,如果有多少次没有限制每个对象可用于
我想要什么(给出maxComboCount约束的所有组合= 4):{r1},{r2},{r3},{r1,r1},{r1,r2},{r1,r3},{r2,r2},{r2,r3},{r3,r3} {r1,r1,r1},{r1,r1,r2},{r1,r1,r3},{r1,r2,r3}等等......
maxComboCount约束确保no列表大小> 4返回
基本上,我想从n个对象,其中k的范围可以从1到x(任何数量)
你是指“没有重复的可能组合”是什么意思?你是指排列还是别的什么? – Arjang
你能用简单的英文写出你想要的东西吗?我不想检查您的代码,以了解您想要实现的目标。 –
“我需要的场景可能会陷入无限循环”这意味着你做错了什么,因为有或没有重复的元素,组合的数量如果总是有限的(尽管它可以变得非常快)。 – oerkelens