How to find every combination of a list?

Just like a power-set, I want to create a block that find every combination of a list, eg. combinations of({1,2,3}) = {{},{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}}

There are several ways to do this. One way is to use the COMBINATIONS block:


The COMBINATIONS call itself gives a list of eight three-item lists, each of which is either an empty list or a list with one of the original items (1,2,3 in your example). Then the MAP gets rid of the empty slots, so instead of a list of three-item lists we have a list of variable-length lists.

But the official elegant recursive way is to reason "every subset either does or doesn’t include the first element. So, make the power set of all but the first element, then append that to a copy of itself with the first element prepended to all the sublists:

Oooh! :heart_eyes:

This is super awesome, Brian!

I’ve been doing a couple of quick experiments myself yesterday but didn’t come up with such a beautiful and elegant solution. Thank you!

SICP ex. 2.32. :~)

One tricky part is the base case, which doesn’t report an empty list, but rather a list containing an empty list. (The empty set is a subset of itself.)

The other tricky part is using a variable to hold the result of the recursive call. Of course the running time has to be O(2^n) where n is the number of elements in the original set, but if you make two recursive calls I think it’s exponential in the number of subsets!

Just a heads up that you don’t need the grey identity reporter. Leaving a collapsed APPEND works just fine if it is the only block, and you can use explicit input parameters if you want to make it clear. I’ve seen this in the list utilities library as well, that’s why I thought I’d mention it.

Thanks!