Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You want a powerset. Here are all the questions on StackOverflow that mention <a href="https://stackoverflow.com/search?q=%22powerset%22">powersets</a> or <a href="https://stackoverflow.com/search?q=%22power+set%22">power sets</a>.</p> <p>Here is a basic implementation in python:</p> <pre><code>def powerset(s): n = len(s) masks = [1&lt;&lt;j for j in xrange(n)] for i in xrange(2**n): yield [s[j] for j in range(n) if (masks[j] &amp; i)] if __name__ == '__main__': for elem in powerset([1,2,3,4,5]): print elem </code></pre> <p>And here is its output:</p> <pre><code>[] [1] [2] [1, 2] [3] [1, 3] [2, 3] [1, 2, 3] [4] [1, 4] [2, 4] [1, 2, 4] [3, 4] [1, 3, 4] [2, 3, 4] [1, 2, 3, 4] [5] [1, 5] [2, 5] [1, 2, 5] [3, 5] [1, 3, 5] [2, 3, 5] [1, 2, 3, 5] [4, 5] [1, 4, 5] [2, 4, 5] [1, 2, 4, 5] [3, 4, 5] [1, 3, 4, 5] [2, 3, 4, 5] [1, 2, 3, 4, 5] </code></pre> <p>Notice that its first result is the empty set. Change the iteration from this <code>for i in xrange(2**n):</code> to this <code>for i in xrange(1, 2**n):</code> if you want to skip an empty set.</p> <p>Here is the code adapted to produce string output:</p> <pre><code>def powerset(s): n = len(s) masks = [1&lt;&lt;j for j in xrange(n)] for i in xrange(2**n): yield "".join([str(s[j]) for j in range(n) if (masks[j] &amp; i)]) </code></pre> <hr> <p>Edit 2009-10-24</p> <p>Okay, I see you are partial to an implementation in Java. I don't know Java, so I'll meet you halfway and give you code in C#:</p> <pre><code> static public IEnumerable&lt;IList&lt;T&gt;&gt; powerset&lt;T&gt;(IList&lt;T&gt; s) { int n = s.Count; int[] masks = new int[n]; for (int i = 0; i &lt; n; i++) masks[i] = (1 &lt;&lt; i); for (int i = 0; i &lt; (1 &lt;&lt; n); i++) { List&lt;T&gt; newList = new List&lt;T&gt;(n); for (int j = 0; j &lt; n; j++) if ((masks[j] &amp; i) != 0) newList.Add(s[j]); yield return newList; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload