Search code examples
scalasetsubset

find closed sets in a list


I have a list of sets (Scala) and would like to remove all supersets. E.g.

List(Set(1,2,3), Set(1,2), Set(2,1), Set(5,6), Set(5))

I would like to get the following list

List(Set(1,2), Set(5))

I wrote the following function - not sure how robust it is:

 def findClosedSets (array: Array[Set[Int]]) : Array[Set[Int]] = {
  val arrayRight = array.distinct
  val arrayLeft =  arrayRight
  arrayLeft.filter(j => arrayRight.filter(i => i.subsetOf(j)).length==1)
} 

Solution

  • Consider using filter as follows

    mySets.distinct.filter(s => mySets.forall(x => !x.subsetOf(s) || s == x))