I have a Set of items of some type and want to generate its power set.
I searched the web and couldn't find any Scala code that adresses this specific task.
This is what I came up with. It allows you to restrict the cardinality of the sets produced by the length parameter.
def power[T](set: Set[T], length: Int) = { var res = Set[Set[T]]() res ++= set.map(Set(_)) for (i <- 1 until length) res = res.map(x => set.map(x + _)).flatten res }
This will not include the empty set. To accomplish this you would have to change the last line of the method simply to res + Set()
Any suggestions how this can be accomplished in a more functional style?
To calculate the total number of sets present in a power set we have to use the formula: No. of sets in P(S) = 2^n, where n is the number of elements in set S.
A power set is defined as the set or group of all subsets for any given set, including the empty set, which is denoted by {}, or, ϕ. A set that has 'n' elements has 2n subsets in all. For example, let Set A = {1,2,3}, therefore, the total number of elements in the set is 3.
Power set of a finite set is finite. Set S is an element of power set of S which can be written as S ɛ P(S). Empty Set ɸ is an element of power set of S which can be written as ɸ ɛ P(S). Empty set ɸ is subset of power set of S which can be written as ɸ ⊂ P(S).
Looks like no-one knew about it back in July, but there's a built-in method: subsets
.
scala> Set(1,2,3).subsets foreach println Set() Set(1) Set(2) Set(3) Set(1, 2) Set(1, 3) Set(2, 3) Set(1, 2, 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With