Exercise: Powerset
Your task is to implement the powerset
function, which returns a set of all subsets of a given set. Here are a few examples of how it should work:
powerset(setOf()) == setOf(setOf())
powerset(setOf(1)) == setOf(setOf(), setOf(1))
powerset(setOf(1, 2)) == setOf(
setOf(), setOf(1), setOf(2), setOf(1, 2)
)
powerset(setOf(1, 2, 3)) == setOf(
setOf(), setOf(1), setOf(2), setOf(3), setOf(1, 2),
setOf(1, 3), setOf(2, 3), setOf(1, 2, 3)
)
Here is the starting point:
It is easiest to implement this function using recursion. Notice, that a powerset of a set with n elements is a powerset of a set with n-1 elements, plus all elements from the powerset of a set with n-1 elements with the n-th element added.
powerset(setOf()) == setOf(setOf())
powerset(setOf(1)) ==
powerset(setOf()) + powerset(setOf()).eachPlus(1)
powerset(setOf(1,2)) ==
powerset(setOf(1)) + powerset(setOf(1)).eachPlus(2)
powerset(N) == powerset(N/m) + powerset(N/m).eachPlus(m)
This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in functional/collections/Powerset.kt. You can find there starting code and unit tests.
Once you are done with the exercise, you can check your solution here.