Exercise: All possible partitions of a set
Your task is to implement the partitions
function, which returns a set of all possible partitions of a given set. A partition of a set is a grouping of its elements into non-empty subsets, in such a way that every element is included in exactly one subset. Here are a few examples of how it should work:
partitions(setOf(1)) == setOf(setOf(setOf(1)))
partitions(setOf(1, 2)) == setOf(
setOf(setOf(1), setOf(2)),
setOf(setOf(1, 2))
)
partitions(setOf(1, 2, 3)) == setOf(
setOf(setOf(1), setOf(2), setOf(3)),
setOf(setOf(1), setOf(2, 3)),
setOf(setOf(1, 2), setOf(3)),
setOf(setOf(1, 2, 3))
)
Here is the starting point:
It is easiest to implement this function using recursion.
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/Partitions.kt. You can find there starting code and unit tests.
Once you are done with the exercise, you can check your solution here.