Jump to content

Power set: Difference between revisions

(→‎{{header|Go}}: Bug fix. Oschmid identified the bug, but the fix had problems. Here's a better fix.)
Line 2,869:
Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4)))
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}</lang>
}</lang>Another option that produces lazy sequence of the sets:
 
}</lang>Another option that produces lazy sequence of the sets:
<lang scala>def powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet)</lang>
 
A tail-recursive version:
<lang scala>def powerset[A](s: Set[A]) = {
def powerset_rec(acc: List[Set[A]], remaining: List[A]): List[Set[A]] = remaining match {
case Nil => acc
case head :: tail => powerset_rec(acc ++ acc.map(_ + head), tail)
}
powerset_rec(List(Set.empty[A]), s.toList)
}</lang>
 
=={{header|Scheme}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.