C#从列表中获取可能的不同组合
可能已经有了答案,我只是在用错误的术语搜索。如果是这样的话,我很抱歉,如果确实有答案的话,请你给我指出现有的答案 我需要的是能够获取一个列表,并从该列表中生成所有可能的不同组合。我所说的“不同”是指相同的组合不应该以不同的顺序出现 以下是一个例子: 假设我有一个值为“1”、“2”和“3”的列表,那么我希望输出为=“1”、“2”、“3”、“1、2”、“2-3”、“1-2-3” 我对“空白”组合不感兴趣,我不想在多个订单中返回相同的组合。我发现并试图为我工作的大多数代码都有一个主要缺陷,即它将返回所有可能的结果,包括“两三”和“三二”,这在我的情况下是错误的 我目前正在修改的代码来自另一个SO问题(),如下所示:C#从列表中获取可能的不同组合,c#,unique,distinct,combinations,C#,Unique,Distinct,Combinations,可能已经有了答案,我只是在用错误的术语搜索。如果是这样的话,我很抱歉,如果确实有答案的话,请你给我指出现有的答案 我需要的是能够获取一个列表,并从该列表中生成所有可能的不同组合。我所说的“不同”是指相同的组合不应该以不同的顺序出现 以下是一个例子: 假设我有一个值为“1”、“2”和“3”的列表,那么我希望输出为=“1”、“2”、“3”、“1、2”、“2-3”、“1-2-3” 我对“空白”组合不感兴趣,我不想在多个订单中返回相同的组合。我发现并试图为我工作的大多数代码都有一个主要缺陷,即它将返回所
public void GetCombination(System.Collections.Generic.List<string> list)
{
Combinations = new List<string>();
double count = System.Math.Pow(2, list.Count);
for (int i = 1; i <= count - 1; i++)
{
string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
for (int j = 0; j < str.Length; j++)
{
if (str[j] == '1')
{
Combinations.Add(list[j]);
}
}
///Combinations = found;
}
}
public void getcomposition(System.Collections.Generic.List)
{
组合=新列表();
double count=System.Math.Pow(2,list.count);
对于(inti=1;i,这里是使用Martin Smith实现的代码:
class Program {
static void Main(string[] args) {
// find all possible combinations of this list
var input = new [] {"One", "Two", "Three"};
var output = FastPowerSet(input);
Print(output);
Console.ReadLine();
}
static T[][] FastPowerSet<T>(T[] seq) {
var powerSet = new T[1 << seq.Length][];
powerSet[0] = new T[0]; // starting only with empty set
for (var i = 0; i < seq.Length; i++) {
var cur = seq[i];
var count = 1 << i; // doubling list each time
for (var j = 0; j < count; j++) {
var source = powerSet[j];
var destination = powerSet[count + j] = new T[source.Length + 1];
for (var q = 0; q < source.Length; q++)
destination[q] = source[q];
destination[source.Length] = cur;
}
}
return powerSet;
}
static void Print<T>(T[][] seq) {
for (var i = 0; i < seq.Length; i++) {
var line = new StringBuilder();
for (var j = 0; j < seq[i].Length; j++ ) {
line.AppendFormat("{0}, ", seq[i][j]);
}
Console.WriteLine(line);
}
}
}
类程序{
静态void Main(字符串[]参数){
//查找此列表的所有可能组合
变量输入=新[]{“一”、“二”、“三”};
var输出=快速功率集(输入);
打印(输出);
Console.ReadLine();
}
静态T[]FastPowerSet(T[]序列){
var powerSet=new T[1您从未问过一个问题,您遇到的问题是什么。当前代码没有返回正确的输出…问题是,如何使用C#查找不同的组合?您太棒了,我认为这将非常有效。非常感谢!