Following are two pieces of code I used to compute power sets of elements in a list
code 1)
public static List<List<int>> getCpower(List<int> list)
{
var result = new List<List<int>>();
for (int i = 0; i < (1 << list.Count); i++)
{
var sublist = new List<int>();
for (int j = 0; j < list.Count; j++)
{ if ((i & (1 << j)) != 0)
{ sublist.Add(list[j]);
}
}
result.Add(sublist);
}
return result;
}
code 2)
public static List<List<int>> getCpower(List<int> list)
{
var result = new List<List<int>>();var sublist = new List<int>();
for (int i = 0; i < (1 << list.Count); i++)
{
sublist.Clear();sublist.TrimExcess();
for (int j = 0; j < list.Count; j++)
{ if ((i & (1 << j)) != 0)
{ sublist.Add(list[j]);
}
}
result.Add(sublist);
}
return result;
}
The first code used a new statement and if i try to find out powersets of list with count 30 then OutOfMemoryException arises.So to save memory i used Clear() and TrimExcess() to get the list as if it were initialized using a new statement in code2. But these two codes return different results. I do not get why is this happening. Please help.
Are the two following two pieces not doing the same thing
for(....)
{
var sublist = new List<int>();
for(......)
{
//some code
}
}
and
var sublist = new List<int>();
for(.....)
{
sublist.Clear();sublist.TrimExcess();
for(.... )
{
//some code
}
}
In your second code, you only have a single nested list – you’re adding several references referring to the same sublist, which is pointless.
Have you considered that maybe the reason you’re running out of space with your first code is because you’re fundamentally trying to hold too much data in memory at a time?
You could consider returning an
IEnumerable<List<int>>like this:This will now be lazily evaluated – so you could iterate over the top-level sequence, but unless the lists are retained by the caller, you’ll only have a single list in memory at a time.