views:

32

answers:

1

Given a list of sets...

 var sets = new List<HashSet<int>>(numTags);

How can I remove all the sets that are a proper subset of another?

Is this the best way to do it?

for (int i = 0; i < sets.Count; ++i)
{
    for (int j = 0; j < sets.Count; ++j)
    {
        if (i != j && sets[i].IsProperSubsetOf(sets[j]))
        {
            sets.RemoveAt(i--);
        }
    }
}

I'm decrementing i because I assume everything gets nudged down one after it gets removed so I have to check that slot again.

+3  A: 
    var toRemove = sets.Where(s => sets.Any(superset => s.IsProperSubsetOf(superset))).ToList();

    foreach (var s in toRemove)
        sets.Remove(s);

You don't need s != superset check, cause no set is a proper subset of itself. http://en.wikipedia.org/wiki/Proper_subset#proper_subset

Grozz
Better yet, use `RemoveAll`. `sets.RemoveAll(subset => sets.Any(superset => subset != superset ` Thanks!
Mark
@Grozz: No... I know that, but I changed my mind, I actually do want a regular old subset ;)
Mark