Generate a powerset of a set without keeping a stack in Erlang or Ruby

前端 未结 3 947
感情败类
感情败类 2020-12-10 19:50

I would like to generate a powerset of a rather big set (about 30-50 elements) and I know that it takes 2^n to store the powerset.

Is it possible to gen

3条回答
  •  余生分开走
    2020-12-10 20:23

    One way to generate a powerset of a list (which is in fact the one that your Erlang example uses) is to iterate over all numbers x from 0 to 2^n (exclusive) and for each x, generate the list that contains the ith element of the original list if and only if the ith bit of x is set.

    Since using this approach generating the current list only depends on the value of x and not on any of the previously generated lists, you don't have to keep the lists in memory after using them. So this approach can be used to do what you want.

提交回复
热议问题