DEV Community

Discussion on: Build a PowerSet

 
tomerbendavid profile image
Tomer Ben David • Edited

cool, adding the scala functional :: recursive :: declarative :: concise way to the post :)) .

  def powerSet(set: Set[Int]): Set[Set[Int]] = {

    set.toList match {
      case Nil => Set(Set.empty[Int])
      case x :: xs => powerSet(xs.toSet).map(xsi => xsi + x) ++ powerSet(xs.toSet)
    }
  }

  println(powerSet(Set(1,2,3))) // Set(Set(), Set(3, 1), Set(2), Set(2, 1), Set(3, 2), Set(3), Set(3, 2, 1), Set(1))