Simon Pastuch Simon Pastuch - 1 year ago 88
Scala Question

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)

elm elm
Answer Source

Consider using filter as follows

mySets.distinct.filter(s => mySets.forall(x => !x.subsetOf(s) || s == x))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download