I am trying to create a method that will return all subsets of a set.
For example, if I have a collection 10,20,30, I would like to get the following output
return new List<List<int>>()
{
new List<int>(){10},
new List<int>(){20},
new List<int>(){30},
new List<int>(){10,20},
new List<int>(){10,30},
new List<int>(){20,30},
new List<int>(){10,20,30}
};
because a collection can also be a collection of strings, for example, I want to create a generic method. This is what I developed based on this solution .
static void Main(string[] args)
{
Foo<int>(new int[] { 10, 20, 30});
}
static List<List<T>> Foo<T>(T[] set)
{
List<List<T>> subsets = new List<List<T>>();
for (int i = 1; i < set.Length; i++)
{
subsets.Add(new List<T>(){set[i - 1]});
List<List<T>> newSubsets = new List<List<T>>();
for (int j = 0; j < subsets.Count; j++)
{
var tempList = new List<T>();
tempList.Add(subsets[j][0]);
tempList.Add(subsets[i][0]);
var newSubset = tempList;
newSubsets.Add(newSubset);
}
subsets.AddRange(newSubsets);
}
return null;
}
Edit
Sorry this is wrong, I still get duplicates ...
static List<List<T>> GetSubsets<T>(IEnumerable<T> Set)
{
var set = Set.ToList<T>();
List<List<T>> subsets = new List<List<T>>();
subsets.Add(new List<T>());
for (int i = 1; i < set.Count; i++)
{
subsets.Add(new List<T>(){set[i - 1]});
List<List<T>> newSubsets = new List<List<T>>();
for (int j = 0; j < subsets.Count; j++)
{
var newSubset = new List<T>();
foreach(var temp in subsets[j])
newSubset.Add(temp);
newSubset.Add(set[i]);
newSubsets.Add(newSubset);
}
subsets.AddRange(newSubsets);
}
subsets.Add(new List<T>(){set[set.Count - 1]});
return subsets;
}
Then I could call this method the following:
