Power set: Difference between revisions

59,769 bytes added ,  3 months ago
m
No edit summary
 
(177 intermediate revisions by 71 users not shown)
Line 1:
{{task|Discrete math}}
{{omit from|GUISS}}
A [[set]] is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored.
 
A   [[set]]   is a collection (container) of certain values,
Given a set S, the [[wp:Power_set|power set]] (or powerset) of S, written P(S), or 2<sup>S</sup>, is the set of all subsets of S.<p>'''Task : ''' By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2<sup>S</sup> of S.</p><p>For example, the power set of {1,2,3,4} is {{}, {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}}.</p>
without any particular order, and no repeated values.
 
It corresponds with a finite set in mathematics.
 
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
 
Given a set S, the [[wp:Power_set|power set]] (or powerset) of S, written P(S), or 2<sup>S</sup>, is the set of all subsets of S.
 
 
;Task:
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2<sup>S</sup> of S.
 
 
For example, the power set of &nbsp; &nbsp; {1,2,3,4} &nbsp; &nbsp; is
::: {{}, {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}}.
 
For a set which contains n elements, the corresponding power set has 2<sup>n</sup> elements, including the edge cases of [[wp:Empty_set|empty set]].<br />
 
The power set of the empty set is the set which contains itself (2<sup>0</sup> = 1):<br />
::: <math>\mathcal{P}</math>(<math>\varnothing</math>) = { <math>\varnothing</math> }<br />
 
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (2<sup>1</sup> = 2):<br />
::: <math>\mathcal{P}</math>({<math>\varnothing</math>}) = { <math>\varnothing</math>, { <math>\varnothing</math> } }<br>
 
 
'''Extra credit: ''' Demonstrate that your language supports these last two powersets.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F list_powerset(lst)
V result = [[Int]()]
L(x) lst
result.extend(result.map(subset -> subset [+] [@x]))
R result
 
print(list_powerset([1, 2, 3]))</syntaxhighlight>
 
{{out}}
<pre>
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
</pre>
 
=={{header|ABAP}}==
 
This works for ABAP Version 7.40 and above
 
<syntaxhighlight lang="abap">
report z_powerset.
 
interface set.
methods:
add_element
importing
element_to_be_added type any
returning
value(new_set) type ref to set,
 
remove_element
importing
element_to_be_removed type any
returning
value(new_set) type ref to set,
 
contains_element
importing
element_to_be_found type any
returning
value(contains) type abap_bool,
 
get_size
returning
value(size) type int4,
 
is_equal
importing
set_to_be_compared_with type ref to set
returning
value(equal) type abap_bool,
 
get_elements
exporting
elements type any table,
 
stringify
returning
value(stringified_set) type string.
endinterface.
 
 
class string_set definition.
public section.
interfaces:
set.
 
 
methods:
constructor
importing
elements type stringtab optional,
 
build_powerset
returning
value(powerset) type ref to string_set.
 
 
private section.
data elements type stringtab.
endclass.
 
 
class string_set implementation.
method constructor.
loop at elements into data(element).
me->set~add_element( element ).
endloop.
endmethod.
 
 
method set~add_element.
if not line_exists( me->elements[ table_line = element_to_be_added ] ).
append element_to_be_added to me->elements.
endif.
 
new_set = me.
endmethod.
 
 
method set~remove_element.
if line_exists( me->elements[ table_line = element_to_be_removed ] ).
delete me->elements where table_line = element_to_be_removed.
endif.
 
new_set = me.
endmethod.
 
 
method set~contains_element.
contains = cond abap_bool(
when line_exists( me->elements[ table_line = element_to_be_found ] )
then abap_true
else abap_false ).
endmethod.
 
 
method set~get_size.
size = lines( me->elements ).
endmethod.
 
 
method set~is_equal.
if set_to_be_compared_with->get_size( ) ne me->set~get_size( ).
equal = abap_false.
 
return.
endif.
 
loop at me->elements into data(element).
if not set_to_be_compared_with->contains_element( element ).
equal = abap_false.
 
return.
endif.
endloop.
 
equal = abap_true.
endmethod.
 
 
method set~get_elements.
elements = me->elements.
endmethod.
 
 
method set~stringify.
stringified_set = cond string(
when me->elements is initial
then `∅`
when me->elements eq value stringtab( ( `∅` ) )
then `{ ∅ }`
else reduce string(
init result = `{ `
for element in me->elements
next result = cond string(
when element eq ``
then |{ result }∅, |
when strlen( element ) eq 1 and element ne `∅`
then |{ result }{ element }, |
else |{ result }\{{ element }\}, | ) ) ).
 
stringified_set = replace(
val = stringified_set
regex = `, $`
with = ` }`).
endmethod.
 
 
method build_powerset.
data(powerset_elements) = value stringtab( ( `` ) ).
 
loop at me->elements into data(element).
do lines( powerset_elements ) times.
if powerset_elements[ sy-index ] ne `∅`.
append |{ powerset_elements[ sy-index ] }{ element }| to powerset_elements.
else.
append element to powerset_elements.
endif.
enddo.
endloop.
 
powerset = new string_set( powerset_elements ).
endmethod.
endclass.
 
 
start-of-selection.
data(set1) = new string_set( ).
data(set2) = new string_set( ).
data(set3) = new string_set( ).
 
write: |𝑷( { set1->set~stringify( ) } ) -> { set1->build_powerset( )->set~stringify( ) }|, /.
 
set2->set~add_element( `∅` ).
write: |𝑷( { set2->set~stringify( ) } ) -> { set2->build_powerset( )->set~stringify( ) }|, /.
 
set3->set~add_element( `1` )->add_element( `2` )->add_element( `3` )->add_element( `3` )->add_element( `4`
)->add_element( `4` )->add_element( `4` ).
write: |𝑷( { set3->set~stringify( ) } ) -> { set3->build_powerset( )->set~stringify( ) }|, /.
</syntaxhighlight>
 
{{out}}
 
<pre>
𝑷( ∅ ) -> { ∅ }
 
𝑷( { ∅ } ) -> { ∅, {∅} }
 
𝑷( { 1, 2, 3, 4 } ) -> { ∅, 1, 2, {12}, 3, {13}, {23}, {123}, 4, {14}, {24}, {124}, {34}, {134}, {234}, {1234} }
</pre>
 
For a set which contains n elements, the corresponding power set has 2<sup>n</sup> elements, including the edge cases of [[wp:Empty_set|empty set]].<p>The power set of the empty set is the set which contains itself (2<sup>0</sup> = 1):</p>
<math>\mathcal{P}</math>(<math>\varnothing</math>) = { <math>\varnothing</math> }
<p>And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (2<sup>1</sup> = 2):</p>
<math>\mathcal{P}</math>({<math>\varnothing</math>}) = { <math>\varnothing</math>, { <math>\varnothing</math> } }
=={{header|Ada}}==
 
{{incomplete|Ada|It shows no proof of the cases with empty sets.}}This solution prints the power set of words read from the command line.<lang ada>with Ada.Text_IO, Ada.Command_Line;
A solution (without recursion) that prints the power set of the n arguments passed by the command line. The idea is that the i'th bit of a natural between 0 and <math>2^n-1</math> indicates whether or not we should put the i'th element of the command line inside the set.
 
<syntaxhighlight lang="ada">
with Ada.Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Command_Line;
procedure Power_Setpowerset is
type List is array (Positive range <>) of Positive;
Empty: List(1 .. 0);
procedure Print_All_Subsets(Set: List; Printable: List:= Empty) is
procedure Print_Set(Items: List) is
First: Boolean := True;
begin
Ada.Text_IO.Put("{ ");
for Item of Items loop
if First then
First := False; -- no comma needed
else
Ada.Text_IO.Put(", "); -- comma, to separate the items
end if;
Ada.Text_IO.Put(Ada.Command_Line.Argument(Item));
end loop;
Ada.Text_IO.Put_Line(" }");
end Print_Set;
Tail: List := Set(Set'First+1 .. Set'Last);
begin
if Set = Empty then
Print_Set(Printable);
else
Print_All_Subsets(Tail, Printable & Set(Set'First));
Print_All_Subsets(Tail, Printable);
end if;
end Print_All_Subsets;
Set: List(1 .. Ada.Command_Line.Argument_Count);
begin
for Iset in Set'Range0..2**Argument_Count-1 loop -- initialize set
Put ("{");
Set(I) := I;
declare
end loop;
k : natural := set;
Print_All_Subsets(Set); -- do the work
first : boolean := true;
end Power_Set;</lang>{{out}}<pre>>./power_set cat dog mouse
begin
{ cat, dog, mouse }
for i in 1..Argument_Count loop
{ cat, dog }
if k mod 2 = 1 then
{ cat, mouse }
Put ((if first then "" else ",") & Argument (i));
{ cat }
first := false;
{ dog, mouse }
end if;
{ dog }
k := k / 2; -- we go to the next bit of "set"
{ mouse }
end loop;
{ }
end;
>./power_set 1 2
Put_Line("}");
{ 1, 2 }
end loop;
{ 1 }
end powerset;
{ 2 }
</syntaxhighlight>
{ }</pre>
 
 
{{out}}
 
<pre>>./powerset a b c d
{}
{a}
{b}
{a,b}
{c}
{a,c}
{b,c}
{a,b,c}
{d}
{a,d}
{b,d}
{a,b,d}
{c,d}
{a,c,d}
{b,c,d}
{a,b,c,d}</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - no extensions to language used}}
{{incomplete|ALGOL 68|It shows no proof of the cases with empty sets.}}{{works with|ALGOL 68|Revision 1 - no extensions to language used}}{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
 
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
 
Requires: ALGOL 68g mk14.1+<lang algol68>MODE MEMBER = INT;
<syntaxhighlight lang="algol68">MODE MEMBER = INT;
 
PROC power set = ([]MEMBER s)[][]MEMBER:(
Line 93 ⟶ 328:
printf(($"set["d"] = "$,member, repr set, set[member],$l$))
OD
)</syntaxhighlight>
)</lang>{{out}}<pre>set[1] = ();
{{out}}
<pre>
set[1] = ();
set[2] = (1);
set[3] = (2);
Line 100 ⟶ 338:
set[6] = (1, 4);
set[7] = (2, 4);
set[8] = (1, 2, 4);</pre>
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
 
<syntaxhighlight lang="apl">ps←(↓∘⍉(2/⍨≢)⊤(⍳2*≢))(/¨)⊂</syntaxhighlight>
 
{{out}}
 
<!-- note: "line-height: 100%" makes Dyalog's boxed output look better.
Don't know why it wasn't already 100% though. -->
 
<pre style='line-height: 100%;'> ps 1 2 3 4
┌─┬─┬───┬─┬───┬───┬─────┬─┬───┬───┬─────┬───┬─────┬─────┬───────┬┐
│4│3│3 4│2│2 4│2 3│2 3 4│1│1 4│1 3│1 3 4│1 2│1 2 4│1 2 3│1 2 3 4││
└─┴─┴───┴─┴───┴───┴─────┴─┴───┴───┴─────┴───┴─────┴─────┴───────┴┘</pre>
 
<pre style='line-height: 100%;'> ps ⍬
┌┐
││
└┘</pre>
 
<pre style='line-height: 100%;'> ps ,⊂⍬
┌──┬┐
│┌┐││
│││││
│└┘││
└──┴┘</pre>
 
 
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
(functional composition examples)
{{Trans|Haskell}}
<syntaxhighlight lang="applescript">-- POWER SET -----------------------------------------------------------------
 
-- powerset :: [a] -> [[a]]
on powerset(xs)
script subSet
on |λ|(acc, x)
script cons
on |λ|(y)
{x} & y
end |λ|
end script
acc & map(cons, acc)
end |λ|
end script
foldr(subSet, {{}}, xs)
end powerset
 
 
-- TEST ----------------------------------------------------------------------
on run
script test
on |λ|(x)
set {setName, setMembers} to x
{setName, powerset(setMembers)}
end |λ|
end script
map(test, [¬
["Set [1,2,3]", {1, 2, 3}], ¬
["Empty set", {}], ¬
["Set containing only empty set", {{}}]])
--> {{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}},
--> {"Empty set", {{}}},
--> {"Set containing only empty set", {{}, {{}}}}}
end run
 
-- GENERIC FUNCTIONS ---------------------------------------------------------
 
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">{{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}},
{"Empty set", {{}}},
{"Set containing only empty set", {{}, {{}}}}}</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">print powerset [1 2 3 4]</syntaxhighlight>
 
{{out}}
 
<pre>[2 3 4] [] [1 2 4] [1 2 3 4] [1 3 4] [1] [2] [1 3] [3 4] [4] [1 4] [3] [1 2] [2 3] [1 2 3] [2 4]</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="text">
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
//
(* ****** ****** *)
//
extern
fun
Power_set(xs: list0(int)): void
//
(* ****** ****** *)
 
// Helper: fast power function.
fun power(n: int, p: int): int =
if p = 1 then n
else if p = 0 then 1
else if p % 2 = 0 then power(n*n, p/2)
else n * power(n, p-1)
 
fun print_list(list: list0(int)): void =
case+ list of
| nil0() => println!(" ")
| cons0(car, crd) =>
let
val () = begin print car; print ','; end
val () = print_list(crd)
in
end
 
fun get_list_length(list: list0(int), length: int): int =
case+ list of
| nil0() => length
| cons0(car, crd) => get_list_length(crd, length+1)
 
 
fun get_list_from_bit_mask(mask: int, list: list0(int), result: list0(int)): list0(int) =
if mask = 0 then result
else
case+ list of
| nil0() => result
| cons0(car, crd) =>
let
val current: int = mask % 2
in
if current = 0 then
get_list_from_bit_mask(mask >> 1, crd, result)
else
get_list_from_bit_mask(mask >> 1, crd, list0_cons(car, result))
end
 
 
implement
Power_set(xs) = let
val len: int = get_list_length(xs, 0)
val pow: int = power(2, len)
fun loop(mask: int, list: list0(int)): void =
if mask > 0 && mask >= pow then ()
else
let
val () = print_list(get_list_from_bit_mask(mask, list, list0_nil()))
in
loop(mask+1, list)
end
in
loop(0, xs)
end
 
(* ****** ****** *)
 
implement
main0() =
let
val xs: list0(int) = cons0(1, list0_pair(2, 3))
in
Power_set(xs)
end (* end of [main0] *)
 
(* ****** ****** *)
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
{{incomplete|AutoHotkey|It shows no proof of the cases with empty sets.}}ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=147 discussion]<lang autohotkey>a = 1,a,-- ; elements separated by commas
<syntaxhighlight lang="autohotkey">a = 1,a,-- ; elements separated by commas
StringSplit a, a, `, ; a0 = #elements, a1,a2,... = elements of the set
 
Line 112 ⟶ 562:
t .= "}`n{" ; new subsets in new lines
}
MsgBox % RegExReplace(SubStr(t,1,StrLen(t)-1),",}","}")</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
=={{header|AWK}}==
{{incomplete|BBC BASIC|It shows no proof of the cases with empty sets.}}The elements of a set are represented as the bits in an integer (hence the maximum size of set is 32).<lang bbcbasic> DIM list$(3) : list$() = "1", "2", "3", "4"
<syntaxhighlight lang="awk">cat power_set.awk
#!/usr/local/bin/gawk -f
 
# User defined function
function tochar(l,n, r) {
while (l) { n--; if (l%2 != 0) r = r sprintf(" %c ",49+n); l = int(l/2) }; return r
}
 
# For each input
{ for (i=0;i<=2^NF-1;i++) if (i == 0) printf("empty\n"); else printf("(%s)\n",tochar(i,NF)) }
</syntaxhighlight>
 
{{out}}
<pre>
$ gawk -f power_set.awk
1 2 3 4
empty
( 4 )
( 3 )
( 4 3 )
( 2 )
( 4 2 )
( 3 2 )
( 4 3 2 )
( 1 )
( 4 1 )
( 3 1 )
( 4 3 1 )
( 2 1 )
( 4 2 1 )
( 3 2 1 )
( 4 3 2 1 )
</pre>
 
=={{header|BASIC}}==
==={{header|BBC BASIC}}===
The elements of a set are represented as the bits in an integer (hence the maximum size of set is 32).
<syntaxhighlight lang="bbcbasic"> DIM list$(3) : list$() = "1", "2", "3", "4"
PRINT FNpowerset(list$())
END
Line 130 ⟶ 618:
s$ += "},"
NEXT i%
= LEFT$(s$) + "}"</langsyntaxhighlight>{{out}}
{{out}}
{{},{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}}
<pre>
{{},{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}}
</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">P ← (⥊·↕2⥊˜≠)/¨<</syntaxhighlight>
 
{{out}}
<pre>
P 1‿2‿3‿4‿5
⟨ ⟨⟩ ⟨ 5 ⟩ ⟨ 4 ⟩ ⟨ 4 5 ⟩ ⟨ 3 ⟩ ⟨ 3 5 ⟩ ⟨ 3 4 ⟩ ⟨ 3 4 5 ⟩ ⟨ 2 ⟩ ⟨ 2 5 ⟩ ⟨ 2 4 ⟩ ⟨ 2 4 5 ⟩ ⟨ 2 3 ⟩ ⟨ 2 3 5 ⟩ ⟨ 2 3 4 ⟩ ⟨ 2 3 4 5 ⟩ ⟨ 1 ⟩ ⟨ 1 5 ⟩ ⟨ 1 4 ⟩ ⟨ 1 4 5 ⟩ ⟨ 1 3 ⟩ ⟨ 1 3 5 ⟩ ⟨ 1 3 4 ⟩ ⟨ 1 3 4 5 ⟩ ⟨ 1 2 ⟩ ⟨ 1 2 5 ⟩ ⟨ 1 2 4 ⟩ ⟨ 1 2 4 5 ⟩ ⟨ 1 2 3 ⟩ ⟨ 1 2 3 5 ⟩ ⟨ 1 2 3 4 ⟩ ⟨ 1 2 3 4 5 ⟩ ⟩
</pre>
 
=={{header|Bracmat}}==
{{incomplete|Bracmat|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="bracmat">( ( powerset
= done todo first
. !arg:(?done.?todo)
Line 142 ⟶ 643:
)
& out$(powerset$(.1 2 3 4))
);</syntaxhighlight>
);</lang>{{out}}<pre> 1 2 3 4
{{out}}
<pre> 1 2 3 4
, 1 2 3
, 1 2 4
Line 158 ⟶ 661:
, 4
,</pre>
 
=={{header|Burlesque}}==
 
{{incomplete|Burlesque|It shows no proof of the cases with empty sets.}}<lang burlesque>blsq ) {1 2 3 4}R@
<syntaxhighlight lang="burlesque">
{{} {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}}</lang>
blsq ) {1 2 3 4}R@
{{} {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}}
</syntaxhighlight>
 
=={{header|C}}==
{{incomplete|C|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="c">#include <stdio.h>
 
struct node {
Line 193 ⟶ 700:
powerset(argv + 1, argc - 1, 0);
return 0;
}</syntaxhighlight>
}</lang>{{out}}<pre>% ./a.out 1 2 3
{{out}}
<pre>
% ./a.out 1 2 3
[ ]
[ 3 ]
Line 201 ⟶ 711:
[ 3 1 ]
[ 2 1 ]
[ 3 2 1 ]</pre>
</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">
public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}
 
public void PowerSetofColors()
{
var colors = new List<KnownColor> { KnownColor.Red, KnownColor.Green,
KnownColor.Blue, KnownColor.Yellow };
var result = GetPowerSet(colors);
Console.Write( string.Join( Environment.NewLine,
result.Select(subset =>
string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}
 
</syntaxhighlight>
 
{{out}}
<pre>
Red
Green
Red,Green
Blue
Red,Blue
Green,Blue
Red,Green,Blue
Yellow
Red,Yellow
Green,Yellow
Red,Green,Yellow
Blue,Yellow
Red,Blue,Yellow
Green,Blue,Yellow
Red,Green,Blue,Yellow
</pre>
 
An alternative implementation for an arbitrary number of elements:
 
<syntaxhighlight lang="csharp">
public IEnumerable<IEnumerable<T>> GetPowerSet<T>(IEnumerable<T> input) {
var seed = new List<IEnumerable<T>>() { Enumerable.Empty<T>() }
as IEnumerable<IEnumerable<T>>;
 
return input.Aggregate(seed, (a, b) =>
a.Concat(a.Select(x => x.Concat(new List<T>() { b }))));
}
</syntaxhighlight>
 
 
Non-recursive version
 
<syntaxhighlight lang="csharp">
using System;
class Powerset
{
static int count = 0, n = 4;
static int [] buf = new int [n];
static void Main()
{
int ind = 0;
int n_1 = n - 1;
for (;;)
{
for (int i = 0; i <= ind; ++i) Console.Write("{0, 2}", buf [i]);
Console.WriteLine();
count++;
if (buf [ind] < n_1) { ind++; buf [ind] = buf [ind - 1] + 1; }
else if (ind > 0) { ind--; buf [ind]++; }
else break;
}
Console.WriteLine("n=" + n + " count=" + count);
}
}
</syntaxhighlight>
 
----------------
 
 
Recursive version
<syntaxhighlight lang="csharp">
using System;
class Powerset
{
static int n = 4;
static int [] buf = new int [n];
 
static void Main()
{
rec(0, 0);
}
 
static void rec(int ind, int begin)
{
for (int i = begin; i < n; i++)
{
buf [ind] = i;
for (int j = 0; j <= ind; j++) Console.Write("{0, 2}", buf [j]);
Console.WriteLine();
rec(ind + 1, buf [ind] + 1);
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
 
{{incomplete|C++|It shows no proof of the cases with empty sets.}}
=== Non-recursive version ===
 
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <set>
#include <vector>
Line 282 ⟶ 908:
std::cout << " }\n";
}
}</syntaxhighlight>
}</lang>{{out}}<pre>
 
{{out}}
<pre>
{ }
{ 2 }
Line 300 ⟶ 929:
{ 7 }
</pre>
 
==== C++14 version ====
 
This simplified version has identical output to the previous code.
 
<syntaxhighlight lang="cpp">
#include <set>
#include <iostream>
 
template <class S>
auto powerset(const S& s)
{
std::set<S> ret;
ret.emplace();
for (auto&& e: s) {
std::set<S> rs;
for (auto x: ret) {
x.insert(e);
rs.insert(x);
}
ret.insert(begin(rs), end(rs));
}
return ret;
}
 
int main()
{
std::set<int> s = {2, 3, 5, 7};
auto pset = powerset(s);
 
for (auto&& subset: pset) {
std::cout << "{ ";
char const* prefix = "";
for (auto&& e: subset) {
std::cout << prefix << e;
prefix = ", ";
}
std::cout << " }\n";
}
}
</syntaxhighlight>
 
=== Recursive version ===
 
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <set>
 
Line 326 ⟶ 997:
{
return powerset(s, s.size());
}</lang>
 
=={{header|C sharp|C#}}==
{{incomplete|C sharp|It shows no proof of the cases with empty sets.}}<lang csharp>public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}
</syntaxhighlight>
 
public void PowerSetofColors()
{
var colors = new List<KnownColor> { KnownColor.Red, KnownColor.Green,
KnownColor.Blue, KnownColor.Yellow };
var result = GetPowerSet(colors);
Console.Write( string.Join( Environment.NewLine,
result.Select(subset =>
string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}</lang>
Red
Green
Red,Green
Blue
Red,Blue
Green,Blue
Red,Green,Blue
Yellow
Red,Yellow
Green,Yellow
Red,Green,Yellow
Blue,Yellow
Red,Blue,Yellow
Green,Blue,Yellow
Red,Green,Blue,Yellow
An alternative implementation for an arbitrary number of elements:
<lang csharp> public IEnumerable<IEnumerable<T>> GetPowerSet<T>(IEnumerable<T> input) {
var seed = new List<IEnumerable<T>>() { Enumerable.Empty<T>() }
as IEnumerable<IEnumerable<T>>;
 
return input.Aggregate(seed, (a, b) =>
a.Concat(a.Select(x => x.Concat(new List<T>() { b }))));
}</lang>
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(use '[clojure.math.combinatorics :only [subsets] ])
 
(def S #{1 2 3 4})
 
user> (subsets S)
(() (1) (2) (3) (4) (1 2) (1 3) (1 4) (2 3) (2 4) (3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4) (1 2 3 4))</langsyntaxhighlight>
 
'''Alternate solution''', with no dependency on third-party library:
<langsyntaxhighlight Clojurelang="clojure">(defn powerset [coll]
(reduce (fn [a x]
(->>into a (map #(conj % x)) a))
(map #(set (concat #{x} %)))
(concat a)
set))
#{#{}} coll))
 
(powerset #{1 2 3})</langsyntaxhighlight>
<syntaxhighlight lang="clojure">#{#{} #{1} #{2} #{1 2} #{3} #{1 3} #{2 3} #{1 2 3}}</syntaxhighlight>
 
'''Using bit-test''':
see: https://clojuredocs.org/clojure.core/bit-test#example-5d401face4b0ca44402ef78b
<syntaxhighlight lang="clojure">(defn powerset [coll]
(let [cnt (count coll)
bits (Math/pow 2 cnt)]
(for [i (range bits)]
(for [j (range i)
:while (< j cnt)
:when (bit-test i j)]
(nth coll j)))))
 
(powerset [1 2 3])</syntaxhighlight>
<syntaxhighlight lang="clojure">(() (1) (2) (1 2) (3) (1 3) (2 3) (1 2 3))</syntaxhighlight>
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
{{incomplete|CoffeeScript|It shows no proof of the cases with empty sets.}}<lang coffeescript>print_power_set = (arr) ->
print_power_set = (arr) ->
console.log "POWER SET of #{arr}"
for subset in power_set(arr)
Line 420 ⟶ 1,060:
print_power_set []
print_power_set [4, 2, 1]
print_power_set ['dog', 'c', 'b', 'a']</lang>{{out}}<pre>> coffee power_set.coffee
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
> coffee power_set.coffee
POWER SET of
[]
Line 448 ⟶ 1,092:
[ 'dog', 'c', 'a' ]
[ 'dog', 'c', 'b' ]
[ 'dog', 'c', 'b', 'a' ]</pre>
</syntaxhighlight>
 
=={{header|ColdFusion}}==
 
{{incomplete|ColdFusion|It shows no proof of the cases with empty sets.}}Port from the [[#JavaScript|JavaScript]] version, compatible with ColdFusion 8+ or Railo 3+<lang javascript>public array function powerset(required array data)
Port from the [[#JavaScript|JavaScript]] version,
compatible with ColdFusion 8+ or Railo 3+
<syntaxhighlight lang="javascript">public array function powerset(required array data)
{
var ps = [""];
Line 467 ⟶ 1,116:
}
 
var res = powerset([1,2,3,4]);</langsyntaxhighlight>{{out}}
 
["","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"]
{{out}}
<pre>["","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"]</pre>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun powerset (s)
{{incomplete|Common Lisp|It shows no proof of the cases with empty sets.}}<lang lisp>(defun power-set (s)
(if s (mapcan (lambda (x) (list (cons (car s) x) x))
(powerset (cdr s)))
'(())))</syntaxhighlight>
 
{{out}}
> (powerset '(l i s p))
((L I S P) (I S P) (L S P) (S P) (L I P) (I P) (L P) (P) (L I S) (I S) (L S) (S) (L I) (I) (L) NIL)
 
<syntaxhighlight lang="lisp">(defun power-set (s)
(reduce #'(lambda (item ps)
(append (mapcar #'(lambda (e) (cons item e))
Line 477 ⟶ 1,138:
s
:from-end t
:initial-value '(())))</langsyntaxhighlight>{{out}}
{{out}}
>(power-set '(1 2 3))
((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) NIL)
 
 
Alternate, more recursive (same output):
<langsyntaxhighlight lang="lisp">(defun powerset (l)
(if (null l)
(list nil)
(let ((prev (powerset (cdr l))))
(append (mapcar #'(lambda (elt) (cons (car l) elt)) prev)
prev))))</langsyntaxhighlight>
 
 
Imperative-style using LOOP:
<langsyntaxhighlight lang="lisp">(defun powerset (xs)
(loop for i below (expt 2 (length xs)) collect
(loop for j below i for x in xs if (logbitp j i) collect x)))</langsyntaxhighlight>
{{out}}
Output:
>(powerset '(1 2 3)
(NIL (1) (2) (1 2) (3) (1 3) (2 3) (1 2 3))
 
Yet another imperative solution, this time with dolist.
<langsyntaxhighlight lang="lisp">(defun power-set (list)
(let ((pow-set (list nil)))
(dolist (element (reverse list) pow-set)
(dolist (set pow-set)
(push (cons element set) pow-set)))))</langsyntaxhighlight>
{{out}}
Output:
>(power-set '(1 2 3))
((1) (1 3) (1 2 3) (1 2) (2) (2 3) (3) NIL)
 
=={{header|D}}==
This implementation defines a range which *lazily* enumerates the power set.
{{incomplete|D|It shows no proof of the cases with empty sets.}}Version using just arrays (it assumes the input to contain distinct items):<lang d>T[][] powerSet(T)(in T[] s) pure nothrow @safe {
 
auto r = new typeof(return)(1, 0);
<syntaxhighlight lang="d">import std.algorithm;
foreach (e; s) {
import std.range;
typeof(return) rs;
 
foreach (x; r)
auto powerSet(R)(R r)
rs ~= x ~ [e];
{
r ~= rs;
return
}
(1L<<r.length)
return r;
.iota
.map!(i =>
r.enumerate
.filter!(t => (1<<t[0]) & i)
.map!(t => t[1])
);
}
 
unittest
void main() {
{
import std.stdio;
int[] emptyArr;
assert(emptyArr.powerSet.equal!equal([emptyArr]));
assert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]]));
}
 
void main(string[] args)
[1, 2, 3].powerSet.writeln;
{
}</lang>{{out}}
import std.stdio;
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
args[1..$].powerSet.each!writeln;
===Lazy Version===
}</syntaxhighlight>
Compile with -version=power_set2_main to run the main.
<lang d>auto powerSet(T)(T[] xs) pure nothrow @safe {
static struct Result {
T[] xsLocal, output;
size_t len;
size_t bits;
 
An alternative version, which implements the range construct from scratch:
this(T[] xs_) pure nothrow @safe {
this.xsLocal = xs_;
this.output.length = xs_.length;
this.len = 1U << xs_.length;
}
 
<syntaxhighlight lang="d">import std.range;
@property empty() const pure nothrow @safe {
return bits == len;
}
 
struct PowerSet(R)
void popFront() pure nothrow @safe { bits++; }
if (isRandomAccessRange!R)
@property save() pure nothrow @safe { return this; }
{
R r;
size_t position;
 
struct PowerSetItem
T[] front() pure nothrow @safe {
{
size_t pos = 0;
R r;
foreach (immutable size_t i; 0 .. xsLocal.length)
size_t position;
if (bits & (1 << i))
output[pos++] = xsLocal[i];
return output[0 .. pos];
}
}
 
private void advance()
return Result(xs);
{
while (!(position & 1))
{
r.popFront();
position >>= 1;
}
}
 
@property bool empty() { return position == 0; }
@property auto front()
{
advance();
return r.front;
}
void popFront()
{
advance();
r.popFront();
position >>= 1;
}
}
 
@property bool empty() { return position == (1 << r.length); }
@property PowerSetItem front() { return PowerSetItem(r.save, position); }
void popFront() { position++; }
}
 
auto powerSet(R)(R r) { return PowerSet!R(r); }</syntaxhighlight>
version (power_set2_main) {
{{out}}
void main() {
<pre>$ rdmd powerset a b c
import std.stdio;
[]
[1, 2, 3].powerSet.writeln;
["a"]
}
["b"]
}</lang>Same output.
["a", "b"]
["c"]
["a", "c"]
["b", "c"]
["a", "b", "c"]</pre>
 
 
=== Alternative: using folds ===
 
An almost verbatim translation of the Haskell code in D.
 
Since D doesn't foldr, I've also copied Haskell's foldr implementation here.
 
Main difference from the Haskell:
#It isn't lazy (but it could be made so by implementing this as a generator)
 
Main differences from the version above:
#It isn't lazy
#It doesn't rely on integer bit fiddling, so it should work on arrays larger than size_t.
 
<syntaxhighlight lang="d">
// Haskell definition:
// foldr f z [] = z
// foldr f z (x:xs) = x `f` foldr f z xs
S foldr(T, S)(S function(T, S) f, S z, T[] rest) {
return (rest.length == 0) ? z : f(rest[0], foldr(f, z, rest[1..$]));
}
 
// Haskell definition:
//powerSet = foldr (\x acc -> acc ++ map (x:) acc) [[]]
T[][] powerset(T)(T[] set) {
import std.algorithm;
import std.array;
// Note: The types before x and acc aren't needed, so this could be made even more concise, but I think it helps
// to make the algorithm slightly clearer.
return foldr( (T x, T[][] acc) => acc ~ acc.map!(accx => x ~ accx).array , [[]], set );
}
</syntaxhighlight>
 
A [[Power_set/D|set implementation]] and its power set function.
=={{header|Déjà Vu}}==
 
{{incomplete|Déjà Vu|It shows no proof of the cases with empty sets.}}In Déjà Vu, sets are dictionaries with all values <code>true</code> and the default set to <code>false</code>.<lang dejavu>powerset s:
In Déjà Vu, sets are dictionaries with all values <code>true</code> and the default set to <code>false</code>.
 
<syntaxhighlight lang="dejavu">powerset s:
local :out [ set{ } ]
for value in keys s:
Line 573 ⟶ 1,303:
out
 
!. powerset set{ 1 2 3 4 }</syntaxhighlight>
!. powerset set{ 1 2 3 4 }</lang>{{out}}<pre>[ set{ } set{ 4 } set{ 3 4 } set{ 3 } set{ 2 3 } set{ 2 3 4 } set{ 2 4 } set{ 2 } set{ 1 2 } set{ 1 2 4 } set{ 1 2 3 4 } set{ 1 2 3 } set{ 1 3 } set{ 1 3 4 } set{ 1 4 } set{ 1 } ]</pre>
 
{{out}}
<pre>[ set{ } set{ 4 } set{ 3 4 } set{ 3 } set{ 2 3 } set{ 2 3 4 } set{ 2 4 } set{ 2 } set{ 1 2 } set{ 1 2 4 } set{ 1 2 3 4 } set{ 1 2 3 } set{ 1 3 } set{ 1 3 4 } set{ 1 4 } set{ 1 } ]</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Power_set;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
const
n = 4;
 
var
buf: TArray<Integer>;
 
procedure rec(ind, bg: Integer);
begin
for var i := bg to n - 1 do
begin
buf[ind] := i;
for var j := 0 to ind do
write(buf[j]: 2);
writeln;
rec(ind + 1, buf[ind] + 1);
end;
end;
 
begin
SetLength(buf, n);
rec(0,0);
{$IFNDEF UNIX}readln;{$ENDIF}
end.</syntaxhighlight>
 
=={{header|Dyalect}}==
 
{{trans|C#}}
 
<syntaxhighlight lang="dyalect">let n = 4
let buf = Array.Empty(n)
func rec(idx, begin) {
for i in begin..<n {
buf[idx] = i
for j in 0..idx {
print("{0, 2}".Format(buf[j]), terminator: "")
}
print("")
rec(idx + 1, buf[idx] + 1)
}
}
 
rec(0, 0)</syntaxhighlight>
 
=={{header|E}}==
 
{{incomplete|E|It shows no proof of the cases with empty sets.}}[[Category:E examples needing attention]]<lang e>pragma.enable("accumulator")
<syntaxhighlight lang="e">pragma.enable("accumulator")
 
def powerset(s) {
Line 583 ⟶ 1,373:
})
}
}</syntaxhighlight>
}</lang>It would also be possible to define an object which is the powerset of a provided set without actually instantiating all of its members immediately.
 
It would also be possible to define an object which is the powerset of a provided set without actually instantiating all of its members immediately. [[Category:E examples needing attention]]
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(define (set-cons a A)
(make-set (cons a A)))
 
(define (power-set e)
(cond ((null? e)
(make-set (list ∅)))
(else (let [(ps (power-set (cdr e)))]
(make-set
(append ps (map set-cons (circular-list (car e)) ps)))))))
 
(define B (make-set ' ( 🍎 🍇 🎂 🎄 )))
(power-set B)
→ { ∅ { 🍇 } { 🍇 🍎 } { 🍇 🍎 🎂 } { 🍇 🍎 🎂 🎄 } { 🍇 🍎 🎄 } { 🍇 🎂 } { 🍇 🎂 🎄 }
{ 🍇 🎄 } { 🍎 } { 🍎 🎂 } { 🍎 🎂 🎄 } { 🍎 🎄 } { 🎂 } { 🎂 🎄 } { 🎄 } }
 
;; The Von Neumann universe
 
(define V0 (power-set null)) ;; null and ∅ are the same
→ { ∅ }
(define V1 (power-set V0))
→ { ∅ { ∅ } }
(define V2 (power-set V1))
→ { ∅ { ∅ } { ∅ { ∅ } } { { ∅ } } }
(define V3 (power-set V2))
→ { ∅ { ∅ } { ∅ { ∅ } } …🔃 )
(length V3) → 16
(define V4 (power-set V3))
(length V4) → 65536
;; length V5 = 2^65536 : out of bounds
 
 
</syntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule RC do
use Bitwise
def powerset1(list) do
n = length(list)
max = round(:math.pow(2,n))
for i <- 0..max-1, do: (for pos <- 0..n-1, band(i, bsl(1, pos)) != 0, do: Enum.at(list, pos) )
end
def powerset2([]), do: [[]]
def powerset2([h|t]) do
pt = powerset2(t)
(for x <- pt, do: [h|x]) ++ pt
end
def powerset3([]), do: [[]]
def powerset3([h|t]) do
pt = powerset3(t)
powerset3(h, pt, pt)
end
defp powerset3(_, [], acc), do: acc
defp powerset3(x, [h|t], acc), do: powerset3(x, t, [[x|h] | acc])
end
 
IO.inspect RC.powerset1([1,2,3])
IO.inspect RC.powerset2([1,2,3])
IO.inspect RC.powerset3([1,2,3])
IO.inspect RC.powerset1([])
IO.inspect RC.powerset1(["one"])</syntaxhighlight>
 
{{out}}
<pre>
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
[[1], [1, 3], [1, 2, 3], [1, 2], [2], [2, 3], [3], []]
[[]]
[[], ["one"]]
</pre>
 
=={{header|Erlang}}==
 
{{incomplete|Erlang|It shows no proof of the cases with empty sets.}}
{{out|Generates all subsets of a list with the help of binary}}:
<pre>For [1 2 3]:
For [1 2 3]:
[ ] | 0 0 0 | 0
[ 3] | 0 0 1 | 1
Line 596 ⟶ 1,466:
[1 2 ] | 1 1 0 | 6
[1 2 3] | 1 1 1 | 7
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯</pre><lang erlang>powerset(Lst) ->
</pre>
<syntaxhighlight lang="erlang">powerset(Lst) ->
N = length(Lst),
Max = trunc(math:pow(2,N)),
[[lists:nth(Pos+1,Lst) || Pos <- lists:seq(0,N-1), I band (1 bsl Pos) =/= 0]
|| I <- lists:seq(0,Max-1)].</syntaxhighlight>
|| I <- lists:seq(0,Max-1)].</lang>{{out|Which outputs}}<pre>[[], [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]]</pre>Alternate shorter and more efficient version:<lang erlang>powerset([]) -> [[]];
 
{{out}}
<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]]</code>
 
Alternate shorter and more efficient version:
<syntaxhighlight lang="erlang">powerset([]) -> [[]];
powerset([H|T]) -> PT = powerset(T),
[ [H|X] || X <- PT ] ++ PT.</langsyntaxhighlight>or even more efficient version:<lang erlang>powerset([]) -> [[]];
 
or even more efficient version:
<syntaxhighlight lang="erlang">powerset([]) -> [[]];
powerset([H|T]) -> PT = powerset(T),
powerset(H, PT, PT).
 
powerset(_, [], Acc) -> Acc;
powerset(X, [H|T], Acc) -> powerset(X, T, [[X|H]|Acc]).</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
{{incomplete|F Sharp|It shows no proof of the cases with empty sets.}}almost exact copy of OCaml version
<langsyntaxhighlight lang="fsharp">
let subsets xs = List.foldBack (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]</lang>alternatively with list comprehension<lang fsharp>let rec pow =
</syntaxhighlight>
 
alternatively with list comprehension
 
<syntaxhighlight lang="fsharp">
let rec pow =
function
| [] -> [[]]
| x::xs -> [for i in pow xs do yield! [i;x::i]]</lang>
</syntaxhighlight>
 
=={{header|Factor}}==
{{incomplete|Factor|It shows no proof of the cases with empty sets.}}We use hash sets, denoted by <code>HS{ }</code> brackets, for our sets. <code>members</code> converts from a set to a sequence, and <code><hash-set></code> converts back.<lang factor>USING: kernel prettyprint sequences arrays sets hash-sets ;
<syntaxhighlight lang="factor">USING: kernel prettyprint sequences arrays sets hash-sets ;
IN: powerset
 
: add ( set elt -- newset ) 1array <hash-set> union ;
: powerset ( set -- newset ) members { HS{ } } [ dupd [ add ] curry map append ] reduce <hash-set> ;</langsyntaxhighlight>{{out|Usage}}<pre>( scratchpad ) HS{ 1 2 3 4 } powerset .
Usage:
<syntaxhighlight lang="factor">( scratchpad ) HS{ 1 2 3 4 } powerset .
HS{
HS{ 1 2 3 4 }
Line 638 ⟶ 1,531:
HS{ 1 3 4 }
HS{ 2 3 4 }
}</presyntaxhighlight>
 
=={{header|Forth}}==
{{works with|4tH|3.61.0}}.
{{incomplete|Forth|It shows no proof of the cases with empty sets.}}{{works with|4tH|3.61.0}}.{{trans|C}}<lang forth>: ?print dup 1 and if over args type space then ;
{{trans|C}}
<syntaxhighlight lang="forth">: ?print dup 1 and if over args type space then ;
: .set begin dup while ?print >r 1+ r> 1 rshift repeat drop drop ;
: .powerset 0 do ." ( " 1 i .set ." )" cr loop ;
Line 647 ⟶ 1,543:
: powerset 1 argn check-none check-size 1- lshift .powerset ;
 
powerset</syntaxhighlight>
powerset</lang>{{out}}<pre>$ 4th cxq powerset.4th 1 2 3 4
{{out}}
<pre>
$ 4th cxq powerset.4th 1 2 3 4
( )
( 1 )
Line 663 ⟶ 1,562:
( 1 3 4 )
( 2 3 4 )
( 1 2 3 4 )</pre>
</pre>
 
 
=={{header|FreeBASIC}}==
Los elementos de un conjunto se representan como bits en un número entero (por lo tanto, el tamaño máximo del conjunto es 32).
<syntaxhighlight lang="freebasic">Function ConjuntoPotencia(set() As String) As String
If Ubound(set,1) > 31 Then Print "Set demasiado grande para representarlo como un entero" : Exit Function
If Ubound(set,1) < 0 Then Print "{}": Exit Function ' Set vacío
Dim As Integer i, j
Dim As String s = "{"
For i = Lbound(set) To (2 Shl Ubound(set,1)) - 1
s += "{"
For j = Lbound(set) To Ubound(set,1)
If i And (1 Shl j) Then s += set(j) + ","
Next j
If Right(s,1) = "," Then s = Left(s,Len(s)-1)
s += "},"
Next i
Return Left(s,Len(s)-1) + "}"
End Function
 
Print "El power set de [1, 2, 3, 4] comprende:"
Dim As String set(3) = {"1", "2", "3", "4"}
Print ConjuntoPotencia(set())
Print !"\nEl power set de [] comprende:"
Dim As String set0()
Print ConjuntoPotencia(set0())
Print "El power set de [[]] comprende:"
Dim As String set1(0) = {""}
Print ConjuntoPotencia(set1())
Sleep</syntaxhighlight>
{{out}}
<pre>
El power set de [1, 2, 3, 4] comprende:
{{},{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}}
 
El power set de [] comprende:
{}
 
El power set de [[]] comprende:
{{},{}}
</pre>
 
 
=={{header|Frink}}==
{{incomplete|Frink|It shows no proof of the cases with empty sets.}}Frink's set and array classes have built-in subsets[] methods that return all subsets. If called with an array, the results are arrays. If called with a set, the results are sets.<lang frink>
<syntaxhighlight lang="frink">
a = new set[1,2,3,4]
a.subsets[]</lang>
</syntaxhighlight>
 
=={{header|FunL}}==
{{incomplete|FunL|It shows no proof of the cases with empty sets.}}FunL uses Scala type <code>scala.collection.immutable.Set</code> as it's set type, which has a built-in method <code>subsets</code> returning an (Scala) iterator over subsets.<lang funl>def powerset( s ) = s.subsets().toSet()</lang>
 
The powerset function could be implemented in FunL directly as:<lang funl>def
<syntaxhighlight lang="funl">def powerset( s ) = s.subsets().toSet()</syntaxhighlight>
 
The powerset function could be implemented in FunL directly as:
 
<syntaxhighlight lang="funl">def
powerset( {} ) = {{}}
powerset( s ) =
acc = powerset( s.tail() )
acc + map( x -> {s.head()} + x, acc )</langsyntaxhighlight>
 
or, alternatively as:
<syntaxhighlight lang="funl">import lists.foldr
 
def powerset( s ) = foldr( \x, acc -> acc + map( a -> {x} + a, acc), {{}}, s )
<lang funl>import lists.foldr
 
println( powerset({1, 2, 3, 4}) )</syntaxhighlight>
def powerset( s ) = foldr( (x, acc) -> acc + map( a -> {x} + a, acc), {{}}, s )
 
{{out}}
 
<pre>
{{}, {4}, {1, 2}, {1, 3}, {2, 3, 4}, {3}, {1, 2, 3, 4}, {1, 4}, {1, 2, 3}, {2}, {1, 2, 4}, {1}, {3, 4}, {2, 3}, {2, 4}, {1, 3, 4}}
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Power_set}}
 
'''Solution'''
 
No program needed. Power set is intrinsically supported in Fōrmulæ.
 
'''Case 1.''' Power set of the set {1, 2, 3, 4}
 
[[File:Fōrmulæ - Power set 01.png]]
 
[[File:Fōrmulæ - Power set 02.png]]
 
'''Case 2.''' The power set of the empty set is the set which contains itself.
 
[[File:Fōrmulæ - Power set 03.png]]
 
[[File:Fōrmulæ - Power set 04.png]]
 
'''Case 3.''' The power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set
 
[[File:Fōrmulæ - Power set 05.png]]
 
[[File:Fōrmulæ - Power set 06.png]]
 
'''Case 4.''' Even when it is intrinsically supported, a program can be written:
 
[[File:Fōrmulæ - Power set 07.png]]
 
[[File:Fōrmulæ - Power set 08.png]]
 
[[File:Fōrmulæ - Power set 09.png]]
 
println( powerset({1, 2, 3, 4}) )</lang>{{out}}
{{}, {4}, {1, 2}, {1, 3}, {2, 3, 4}, {3}, {1, 2, 3, 4}, {1, 4}, {1, 2, 3}, {2}, {1, 2, 4}, {1}, {3, 4}, {2, 3}, {2, 4}, {1, 3, 4}}
=={{header|GAP}}==
{{incomplete|GAP|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="gap"># Built-in
Combinations([1, 2, 3]);
# [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]
Line 693 ⟶ 1,682:
Combinations([1, 2, 3, 1]);
# [ [ ], [ 1 ], [ 1, 1 ], [ 1, 1, 2 ], [ 1, 1, 2, 3 ], [ 1, 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ],
# [ 2 ], [ 2, 3 ], [ 3 ] ]</langsyntaxhighlight>
 
=={{header|Go}}==
{{incomplete|Go|It shows no proof of the cases with empty sets.}}No native set type in Go. While the associative array trick mentioned in the task description works well in Go in most situations, it does not work here because we need sets of sets, and converting a general set to a hashable value for a map key is non-trivial.
 
Instead, this solution uses a simple (non-associative) slice as a set representation. To ensure uniqueness, the element interface requires an equality method, which is used by the set add method. Adding elements with the add method ensures the uniqueness property.
set add method. Adding elements with the add method ensures the uniqueness property.
 
TheWhile the "add" and "has" methods make a usable set type, the power set method implemented here doescomputes nota needresult directly without using the add method though. The algorithm ensures that the result will be a valid set as long as the input is a valid set. This allows the more efficient append function to be used.
<syntaxhighlight lang="go">package main
ensures that the result will be a valid set as long as the input is a valid set. This allows the more efficient append function to be used.
<lang go>package main
 
import (
"bytes"
"fmt"
"strconv"
"strings"
)
 
Line 717 ⟶ 1,707:
// the mathematical definition of a set. a.eq(b) must give the same
// result as b.eq(a).
Eq(elementelem) bool
// String result is used only for printable output. Given a, b where
// a.eq(b), it is not required that a.String() == b.String().
Line 727 ⟶ 1,717:
 
func (i Int) Eq(e elem) bool {
j, ok := e.(Int)
return ok && i == j
}
Line 753 ⟶ 1,743:
}
return false
}
 
func (s set) ok() bool {
for i, e0 := range s {
for _, e1 := range s[i+1:] {
if e0.Eq(e1) {
return false
}
}
}
return true
}
 
Line 774 ⟶ 1,775:
// elem.String
func (s set) String() string {
varif buflen(s) bytes.Buffer== 0 {
return "∅"
}
var buf strings.Builder
buf.WriteRune('{')
for _i, e := range s {
if len(r)i > 10 {
buf.WriteRune(' ,')
}
buf.WriteString(e.String())
Line 792 ⟶ 1,796:
var u set
for _, er := range r {
uer := append(u, append(er.(set), es))
u = append(u, append(er[:len(er):len(er)], es))
}
r = append(r, u...)
Line 804 ⟶ 1,809:
s.add(i)
}
fmt.Println(" s:", s, "length:", len(s))
fmt.Println("length =", len(s))
ps := s.powerSet()
fmt.Println(" 𝑷(s):", ps, "length:", len(ps))
fmt.Println("length =", len(ps))
}</lang>{{out}}<pre>{1 2 3 4}
length = 4
{{} {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}}
length = 16</pre>
 
fmt.Println("\n(extra credit)")
=={{header|Groovy}}==
var empty set
{{incomplete|Groovy|It shows no proof of the cases with empty sets.}}Builds on the [[Combinations#Groovy|Combinations]] solution. '''Sets''' are not a "natural" collection type in Groovy. '''Lists''' are much more richly supported. Thus, this solution is liberally sprinkled with coercion from '''Set''' to '''List''' and from '''List''' to '''Set'''.<lang groovy>def comb
fmt.Println(" empty:", empty, "len:", len(empty))
comb = { m, List list ->
def nps = listempty.sizepowerSet()
fmt.Println(" 𝑷(∅):", ps, "len:", len(ps))
m == 0 ?
ps = [[]] :ps.powerSet()
fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps))
(0..(n-m)).inject([]) { newlist, k ->
 
def sublist = (k+1 == n) ? [] : list[(k+1)..<n]
fmt.Println("\n(regression test for earlier bug)")
newlist += comb(m-1, sublist).collect { [list[k]] + it }
s = set{Int(1), Int(2), Int(3), Int(4), Int(5)}
fmt.Println(" s:", s, "length:", len(s), "ok:", s.ok())
ps = s.powerSet()
fmt.Println(" 𝑷(s):", "length:", len(ps), "ok:", ps.ok())
for _, e := range ps {
if !e.(set).ok() {
panic("invalid set in ps")
}
}
}</syntaxhighlight>
{{out}}
<pre>
s: {1,2,3,4} length: 4
𝑷(s): {∅,{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}} length: 16
 
(extra credit)
empty: ∅ len: 0
𝑷(∅): {∅} len: 1
𝑷(𝑷(∅)): {∅,{∅}} len: 2
 
(regression test for earlier bug)
s: {1,2,3,4,5} length: 5 ok: true
𝑷(s): length: 32 ok: true
</pre>
 
=={{header|Groovy}}==
Builds on the [[Combinations#Groovy|Combinations]] solution. '''Sets''' are not a "natural" collection type in Groovy. '''Lists''' are much more richly supported. Thus, this solution is liberally sprinkled with coercion from '''Set''' to '''List''' and from '''List''' to '''Set'''.
<syntaxhighlight lang="groovy">
def powerSetRec(head, tail) {
if (!tail) return [head]
powerSetRec(head, tail.tail()) + powerSetRec(head + [tail.head()], tail.tail())
}
 
def powerSet =(set) { powerSetRec([], set ->as List) as Set}
</syntaxhighlight>
(0..(set.size())).inject([]){ list, i -> list + comb(i,set as List)}.collect { it as LinkedHashSet } as LinkedHashSet
}</lang>Test program:<lang groovy>def vocalists = [ "C", "S", "N", "Y" ] as LinkedHashSet
println "${vocalists}"
println powerSet(vocalists)</lang>
 
Test program:
Output:
<syntaxhighlight lang="groovy">
<pre>[C, S, N, Y]
def vocalists = [ 'C', 'S', 'N', 'Y' ] as Set
[[], [C], [S], [N], [Y], [C, S], [C, N], [C, Y], [S, N], [S, Y], [N, Y], [C, S, N], [C, S, Y], [C, N, Y], [S, N, Y], [C, S, N, Y]]</pre>
println vocalists
println powerSet(vocalists)
</syntaxhighlight>
 
{{out}}
Note: In this example, '''LinkedHashSet''' was used throughout for '''Set''' coercion. This is because '''LinkedHashSet''' preserves the order of input, like a '''List'''. However, if order does not matter you could replace all references to '''LinkedHashSet''' with '''Set'''.
<pre>
[C, S, N, Y]
[[], [Y], [N], [N, Y], [S], [S, Y], [S, N], [S, N, Y], [C], [C, Y], [C, N], [C, N, Y], [C, S], [C, S, Y], [C, S, N], [C, S, N, Y]]
</pre>
 
=={{header|Haskell}}==
{{incomplete|Haskell|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang Haskell="haskell">import Data.Set
import Control.Monad
 
Line 846 ⟶ 1,879:
 
listPowerset :: [a] -> [[a]]
listPowerset = filterM (const [True, False])</syntaxhighlight>
listPowerset = filterM (const [True, False])</lang><tt>listPowerset</tt> describes the result as all possible (using the list monad) filterings (using <tt>filterM</tt>) of the input list, regardless (using <tt>const</tt>) of each item's value. <tt>powerset</tt> simply converts the input and output from lists to sets.
<tt>listPowerset</tt> describes the result as all possible (using the list monad) filterings (using <tt>filterM</tt>) of the input list, regardless (using <tt>const</tt>) of each item's value. <tt>powerset</tt> simply converts the input and output from lists to sets.
 
'''Alternate Solution'''
<langsyntaxhighlight Haskelllang="haskell">powerset [] = [[]]
powerset (head:tail) = acc ++ map (head:) acc where acc = powerset tail</lang> or <lang Haskell>powerset = foldr (\x acc -> acc ++ map (x:) acc) [[]]</langsyntaxhighlight>
or
<syntaxhighlight lang="haskell">powerSet :: [a] -> [[a]]
powerSet = foldr (\x acc -> acc ++ map (x:) acc) [[]]</syntaxhighlight>
 
which could also be understood, in point-free terms, as:
<syntaxhighlight lang="haskell">powerSet :: [a] -> [[a]]
powerSet = foldr ((mappend <*>) . fmap . (:)) (pure [])</syntaxhighlight>
 
Examples:
 
Line 865 ⟶ 1,907:
'''Alternate solution'''
 
A method using only set operations and set mapping is also possible. Ideally, <code>Set</code> would be defined as a Monad, but that's impossible given the constraint that the type of inputs to Set.map (and a few other functions) be ordered.<lang Haskell>import qualified Data.Set as Set
<syntaxhighlight lang="haskell">import qualified Data.Set as Set
type Set=Set.Set
unionAll :: (Ord a) => Set (Set a) -> Set a
Line 879 ⟶ 1,922:
 
powerSet :: (Ord a) => Set a -> Set (Set a)
powerSet = (Set.fold (slift Set.union) (Set.singleton Set.empty)) . Set.map makeSet</langsyntaxhighlight>
{{out|Usage}}:
<syntaxhighlight lang="haskell">
Prelude Data.Set> powerSet fromList [1,2,3]
Prelude Data.Set> powerSet fromList [1,2,3]
fromList [fromList [], fromList [1], fromList [1,2], fromList [1,2,3], fromList [1,3], fromList [2], fromList [2,3], fromList [3]]
fromList [fromList [], fromList [1], fromList [1,2], fromList [1,2,3], fromList [1,3], fromList [2], fromList [2,3], fromList [3]]</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
{{incomplete|Icon|It shows no proof of the cases with empty sets.}}{{incomplete|Unicon|It shows no proof of the cases with empty sets.}}The two examples below show the similarities and differences between constructing an explicit representation of the solution, i.e. a set containing the powerset, and one using generators. The basic recursive algorithm is the same in each case, but wherever the first stores part of the result away, the second uses 'suspend' to immediately pass the result back to the caller. The caller may then decide to store the results in a set, a list, or dispose of each one as it appears.
The two examples below show the similarities and differences between constructing an explicit representation of the solution, i.e. a set containing the powerset, and one using generators. The basic recursive algorithm is the same in each case, but wherever the first stores part of the result away, the second uses 'suspend' to immediately pass the result back to the caller. The caller may then decide to store the results in a set, a list, or dispose of each one as it appears.
 
===Set building===
 
The following version returns a set containing the powerset:<lang Icon>procedure power_set (s)
The following version returns a set containing the powerset:
 
<syntaxhighlight lang="icon">
procedure power_set (s)
result := set ()
if *s = 0
Line 899 ⟶ 1,950:
}
return result
end
end</lang>To test the above procedure:<lang Icon>procedure main ()
</syntaxhighlight>
 
To test the above procedure:
 
<syntaxhighlight lang="icon">
procedure main ()
every s := !power_set (set(1,2,3,4)) do { # requires '!' to generate items in the result set
writes ("[ ")
Line 905 ⟶ 1,962:
write ("]")
}
end</lang>
</syntaxhighlight>
 
{{out}}
Output:
<pre>
[ 3 ]
Line 926 ⟶ 1,984:
[ 2 1 ]
</pre>
 
===Generator===
 
An alternative version, which generates each item in the power set in turn:<lang Icon>procedure power_set (s)
An alternative version, which generates each item in the power set in turn:
 
<syntaxhighlight lang="icon">
procedure power_set (s)
if *s = 0
then suspend set ()
Line 945 ⟶ 2,008:
write ("]")
}
end</lang>
</syntaxhighlight>
 
=={{header|J}}==
 
{{incomplete|J|It shows no proof of the cases with empty sets.}}There are a [http://www.jsoftware.com/jwiki/Essays/Power_Set number of ways] to generate a power set in J. Here's one:
There are a [http://www.jsoftware.com/jwiki/Essays/Power_Set number of ways] to generate a power set in J. Here's one:
<lang j>ps =: #~ 2 #:@i.@^ #</lang>
<syntaxhighlight lang="j">ps =: #~ 2 #:@i.@^ #</syntaxhighlight>
For example:
<langsyntaxhighlight lang="j"> ps 'ACE'
E
Line 958 ⟶ 2,024:
AE
AC
ACE</syntaxhighlight>
ACE</lang>In the typical use, this operation makes sense on collections of unique elements.<lang J> ~.1 2 3 2 1
 
In the typical use, this operation makes sense on collections of unique elements.
 
<syntaxhighlight lang="j"> ~.1 2 3 2 1
1 2 3
#ps 1 2 3 2 1
32
#ps ~.1 2 3 2 1
8</syntaxhighlight>
8</lang>In other words, the power set of a 5 element set has 32 sets where the power set of a 3 element set has 8 sets. Thus if elements of the original "set" were not unique then sets of the power "set" will also not be unique sets.
 
In other words, the power set of a 5 element set has 32 sets where the power set of a 3 element set has 8 sets. Thus if elements of the original "set" were not unique then sets of the power "set" will also not be unique sets.
 
=={{header|Java}}==
{{incomplete|Java|It shows no proof of the cases with empty sets.}}{{works with|Java|1.5+}}
===Recursion===
[[Category:Recursion]]
This implementation sorts each subset, but not the whole list of subsets (which would require a custom comparator). It also destroys the original set.<lang java5>public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
<syntaxhighlight lang="java5">public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
{
if(n<0)
Line 992 ⟶ 2,066:
ps.addAll(tmp);
return ps;
}</langsyntaxhighlight>
 
===Iterative===
The iterative implementation of the above idea. Each subset is in the order that the element appears in the input list. This implementation preserves the input.<lang java5>public static <T> List<List<T>> powerset(Collection<T> list) {
<syntaxhighlight lang="java5">
public static <T> List<List<T>> powerset(Collection<T> list) {
List<List<T>> ps = new ArrayList<List<T>>();
ps.add(new ArrayList<T>()); // add the empty set
Line 1,016 ⟶ 2,093:
}
return ps;
}
}</lang>
</syntaxhighlight>
 
===Binary String===
This implementation works on idea that each element in the original set can either be in the power set or not in it. With <tt>n</tt> elements in the original set, each combination can be represented by a binary string of length <tt>n</tt>. To get all possible combinations, all you need is a counter from 0 to 2<sup>n</sup> - 1. If the k<sup>th</sup> bit in the binary string is 1, the k<sup>th</sup> element of the original set is in this combination.<lang java5>public static <T extends Comparable<? super T>> LinkedList<LinkedList<T>> BinPowSet(
<syntaxhighlight lang="java5">public static <T extends Comparable<? super T>> LinkedList<LinkedList<T>> BinPowSet(
LinkedList<T> A){
LinkedList<LinkedList<T>> ans= new LinkedList<LinkedList<T>>();
Line 1,033 ⟶ 2,113:
}
return ans;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
{{incomplete|JavaScript|It shows no proof of the cases with empty sets.}}Uses a JSON stringifier from http://www.json.org/js.html{{works with|SpiderMonkey}}<lang javascript>function powerset(ary) {
===ES5===
====Iteration====
Uses a JSON stringifier from http://www.json.org/js.html
 
{{works with|SpiderMonkey}}
<syntaxhighlight lang="javascript">function powerset(ary) {
var ps = [[]];
for (var i=0; i < ary.length; i++) {
Line 1,048 ⟶ 2,135:
 
load('json2.js');
print(JSON.stringify(res));</langsyntaxhighlight>{{out}}
 
[[],[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]]
{{out}}
<pre>[[],[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]]</pre>
 
 
====Functional composition====
 
{{trans|Haskell}}
 
<syntaxhighlight lang="javascript">(function () {
 
// translating: powerset = foldr (\x acc -> acc ++ map (x:) acc) [[]]
 
function powerset(xs) {
return xs.reduceRight(function (a, x) {
return a.concat(a.map(function (y) {
return [x].concat(y);
}));
}, [[]]);
}
 
 
// TEST
return {
'[1,2,3] ->': powerset([1, 2, 3]),
'empty set ->': powerset([]),
'set which contains only the empty set ->': powerset([[]])
}
 
})();</syntaxhighlight>
 
{{Out}}
 
<syntaxhighlight lang="javascript">{
"[1,2,3] ->":[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]],
"empty set ->":[[]],
"set which contains only the empty set ->":[[], [[]]]
}</syntaxhighlight>
 
===ES6===
 
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// powerset :: [a] -> [[a]]
const powerset = xs =>
xs.reduceRight((a, x) => [...a, ...a.map(y => [x, ...y])], [
[]
]);
 
 
// TEST
return {
'[1,2,3] ->': powerset([1, 2, 3]),
'empty set ->': powerset([]),
'set which contains only the empty set ->': powerset([
[]
])
};
})()</syntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="javascript">{"[1,2,3] ->":[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]],
"empty set ->":[[]],
"set which contains only the empty set ->":[[], [[]]]}</syntaxhighlight>
 
=={{header|jq}}==
<syntaxhighlight lang="jq">def powerset:
reduce .[] as $i ([[]];
reduce .[] as $r (.; . + [$r + [$i]]));</syntaxhighlight>
Example:
[range(0;10)]|powerset|length
# => 1024
 
Extra credit:
<syntaxhighlight lang="jq">
# The power set of the empty set:
[] | powerset
# => [[]]
 
# The power set of the set which contains only the empty set:
[ [] ] | powerset
# => [[],[[]]]</syntaxhighlight>
====Recursive version====
<syntaxhighlight lang="jq">def powerset:
if length == 0 then [[]]
else .[0] as $first
| (.[1:] | powerset)
| map([$first] + . ) + .
end;</syntaxhighlight>
Example:
[1,2,3]|powerset
# => [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
{{incomplete|Julia|It shows no proof of the cases with empty sets.}}<lang julia>function powerset (x)
function powerset(x::Vector{T})::Vector{Vector{T}} where T
result = {{}}
for i in x, jresult = 1:length(result)Vector{T}[[]]
for elem in x, j in eachindex(result)
push!(result, [result[j],i])
push!(result, [result[j] ; elem])
end
result end
result
end</lang>{{Out}}
end
julia> show(powerset({1,2,3}))
</syntaxhighlight>
{{},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}}
{{Out}}
<pre>
julia> show(powerset([1,2,3]))
[Int64[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
</pre>
 
===Non-Mutating Solution===
<syntaxhighlight lang="julia">
using Base.Iterators
 
function bitmask(u, max_size)
res = BitArray(undef, max_size)
res.chunks[1] = u%UInt64
res
end
 
function powerset(input_collection::Vector{T})::Vector{Vector{T}} where T
num_elements = length(input_collection)
bitmask_map(x) = Iterators.map(y -> bitmask(y, num_elements), x)
getindex_map(x) = Iterators.map(y -> input_collection[y], x)
 
UnitRange(0, (2^num_elements)-1) |>
bitmask_map |>
getindex_map |>
collect
end
</syntaxhighlight>
{{Out}}
<pre>
julia> show(powerset([1,2,3]))
[Int64[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
</pre>
 
=={{header|K}}==
<syntaxhighlight lang="k">
{{incomplete|K|It shows no proof of the cases with empty sets.}}<lang K>
ps:{x@&:'+2_vs!_2^#x}
</syntaxhighlight>
</lang>Usage:<pre>
Usage:
<syntaxhighlight lang="k">
ps "ABC"
(""
Line 1,072 ⟶ 2,287:
"AC"
"AB"
"ABC")</pre>
</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// purely functional & lazy version, leveraging recursion and Sequences (a.k.a. streams)
fun <T> Set<T>.subsets(): Sequence<Set<T>> =
when (size) {
0 -> sequenceOf(emptySet())
else -> {
val head = first()
val tail = this - head
tail.subsets() + tail.subsets().map { setOf(head) + it }
}
}
 
// if recursion is an issue, you may change it this way:
 
fun <T> Set<T>.subsets(): Sequence<Set<T>> = sequence {
when (size) {
0 -> yield(emptySet<T>())
else -> {
val head = first()
val tail = this@subsets - head
yieldAll(tail.subsets())
for (subset in tail.subsets()) {
yield(setOf(head) + subset)
}
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Power set of setOf(1, 2, 3, 4) comprises:
[]
[4]
[3]
[3, 4]
[2]
[2, 4]
[2, 3]
[2, 3, 4]
[1]
[1, 4]
[1, 3]
[1, 3, 4]
[1, 2]
[1, 2, 4]
[1, 2, 3]
[1, 2, 3, 4]
 
Power set of emptySet<Any>() comprises:
[]
 
Power set of setOf(emptySet<Any>()) comprises:
[]
[[]]
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def powerset
 
{def powerset.r
{lambda {:ary :ps :i}
{if {= :i {A.length :ary}}
then :ps
else {powerset.r :ary
{powerset.rr :ary :ps {A.length :ps} :i 0}
{+ :i 1}} }}}
 
{def powerset.rr
{lambda {:ary :ps :len :i :j}
{if {= :j :len}
then :ps
else {powerset.rr :ary
{A.addlast! {A.concat {A.get :j :ps}
{A.new {A.get :i :ary}}}
:ps}
:len
:i
{+ :j 1}} }}}
 
{lambda {:ary}
{A.new {powerset.r :ary {A.new {A.new}} 0}}}}
 
-> powerset
 
{powerset {A.new 1 2 3 4}}
-> [[],[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]]]
 
</syntaxhighlight>
 
=={{header|Logo}}==
{{incomplete|Logo|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="logo">to powerset :set
if empty? :set [output [[]]]
localmake "rest powerset butfirst :set
Line 1,081 ⟶ 2,389:
 
show powerset [1 2 3]
[[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []]</langsyntaxhighlight>
 
=={{header|Logtalk}}==
{{incomplete|Logtalk|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="logtalk">:- object(set).
 
:- public(powerset/2).
Line 1,108 ⟶ 2,416:
reverse(Tail, [Head| List], Reversed).
 
:- end_object.</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight lang="logtalk">| ?- set::powerset([1, 2, 3, 4], PowerSet).
 
PowerSet = [[],[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]]
yes</langsyntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
{{incomplete|Lua|It shows no proof of the cases with empty sets.}}<lang lua>
--returns the powerset of s, out of order.
function powerset(s, start)
Line 1,149 ⟶ 2,458:
return ret
end
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
{{incomplete|M4|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang M4="m4">define(`for',
`ifelse($#, 0, ``$0'',
eval($2 <= $3), 1,
Line 1,172 ⟶ 2,482:
`{powerpart(0, substr(`$1', 1, eval(len(`$1') - 2)))}')dnl
dnl
powerset(`{a,b,c}')</langsyntaxhighlight>
{{},{a},{a,b},{a,b,c},{a,c},{b},{b,c},{c}}
=={{header|Maple}}==
{{incomplete|Maple|It shows no proof of the cases with empty sets.}}<lang Maple>with(combinat):
 
powerset({1,2,3,4});</lang>{{out}}
<pre>
{{}, {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4},
{{},{a},{a,b},{a,b,c},{a,c},{b},{b,c},{c}}
</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
combinat:-powerset({1,2,3,4});
</syntaxhighlight>
{{out}}
<pre>
{{}, {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4},
 
{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}}
</pre>
=={{header|Mathematica}}==
 
{{incomplete|Mathematica|It shows no proof of the cases with empty sets.}}Built-in function that either gives all possible subsets, subsets with at most n elements, subsets with exactly n elements or subsets containing between n and m elements. Example of all subsets:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Subsets[{a, b, c}]</lang>gives:
Built-in function that either gives all possible subsets,
{{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}}
subsets with at most n elements, subsets with exactly n elements
or subsets containing between n and m elements.
Example of all subsets:
<syntaxhighlight lang="mathematica">Subsets[{a, b, c}]</syntaxhighlight>
gives:
<syntaxhighlight lang="mathematica">{{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}}</syntaxhighlight>
Subsets[list, {n, Infinity}] gives all the subsets that have n elements or more.
 
Subsets[list, n] gives all the subsets that have at most n elements.
 
Subsets[list, {n}] gives all the subsets that have exactly n elements.
 
Subsets[list, {m,n}] gives all the subsets that have between m and n elements.
 
=={{header|MATLAB}}==
 
Sets are not an explicit data type in MATLAB, but cell arrays can be used for the same purpose. In fact, cell arrays have the benefit of containing any kind of data structure. So, this powerset function will work on a set of any type of data structure, without the need to overload any operators.<lang MATLAB>function pset = powerset(theSet)
Sets are not an explicit data type in MATLAB, but cell arrays can be used for the same purpose. In fact, cell arrays have the benefit of containing any kind of data structure. So, this powerset function will work on a set of any type of data structure, without the need to overload any operators.
 
<syntaxhighlight lang="matlab">function pset = powerset(theSet)
 
pset = cell(size(theSet)); %Preallocate memory
Line 1,203 ⟶ 2,537:
end
end</langsyntaxhighlight>
 
Sample Usage:
Powerset of the set of the empty set.<lang MATLAB>powerset({{}})
<syntaxhighlight lang="matlab">powerset({{}})
 
ans =
 
{} {1x1 cell} %This is the same as { {},{{}} }</langsyntaxhighlight>
 
Powerset of { {1,2},3 }.
<langsyntaxhighlight MATLABlang="matlab">powerset({{1,2},3})
 
ans =
 
{1x0 cell} {1x1 cell} {1x1 cell} {1x2 cell} %This is the same as { {},{{1,2}},{3},{{1,2},3} }</langsyntaxhighlight>
 
=={{header|Maxima}}==
{{incomplete|Maxima|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="maxima">powerset({1, 2, 3, 4});
/* {{}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 4}, {1, 3}, {1, 3, 4},
{1, 4}, {2}, {2, 3}, {2, 3, 4}, {2, 4}, {3}, {3, 4}, {4}} */</langsyntaxhighlight>
=={{header|Nimrod}}==
{{incomplete|Nimrod|It shows no proof of the cases with empty sets.}}<lang nimrod>import sets, hashes
 
=={{header|Nim}}==
proc hash(x): THash =
<syntaxhighlight lang="nim">import sets, hashes
proc hash(x: HashSet[int]): Hash =
var h = 0
for i in x: h = h !& hash(i)
result = !$h
proc powerset[T](inset: HashSet[T]): HashSet[HashSet[T]] =
result.incl(initHashSet[T]()) # Initialized with empty set.
for val in inset:
let previous = result
for aSet in previous:
var newSet = aSet
newSet.incl(val)
result.incl(newSet)
echo powerset([1,2,3,4].toHashSet())</syntaxhighlight>
 
{{out}}
proc powerset[T](inset: TSet[T]): auto =
<pre>{{4, 3, 1}, {3, 2, 1}, {3}, {3, 1}, {2}, {4, 3, 2, 1}, {}, {4, 2}, {4, 2, 1}, {4, 3, 2}, {1}, {3, 2}, {4, 3}, {4}, {4, 1}, {2, 1}}
result = toSet([initSet[T]()])
</pre>
 
for i in inset:
var tmp = result
for j in result:
var k = j
k.incl(i)
tmp.incl(k)
result = tmp
 
echo powerset(toSet([1,2,3,4]))</lang>
=={{header|Objective-C}}==
{{incomplete|Objective-C|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="objc">#import <Foundation/Foundation.h>
 
+ (NSArray *)powerSetForArray:(NSArray *)array {
Line 1,258 ⟶ 2,598:
}
return subsets;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
{{incomplete|OCaml|It shows no proof of the cases with empty sets.}}The standard library already implements a proper ''Set'' datatype. As the base type is unspecified, the powerset must be parameterized as a module. Also, the library is lacking a ''map'' operation, which we have to implement first.<lang ocaml>module PowerSet(S: Set.S) =
The standard library already implements a proper ''Set'' datatype. As the base type is unspecified, the powerset must be parameterized as a module. Also, the library is lacking a ''map'' operation, which we have to implement first.
 
<syntaxhighlight lang="ocaml">module PowerSet(S: Set.S) =
struct
 
Line 1,276 ⟶ 2,620:
;;
 
end;; (* PowerSet *)</syntaxhighlight>
end;; (* PowerSet *)</lang>version for lists:<lang ocaml>let subsets xs = List.fold_right (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]</lang>
 
version for lists:
<syntaxhighlight lang="ocaml">let subsets xs = List.fold_right (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]</syntaxhighlight>
 
=={{header|OPL}}==
 
{{incomplete|OPL|It shows no proof of the cases with empty sets.}}<lang OPL>{string} s={"A","B","C","D"};
<syntaxhighlight lang="opl">
{string} s={"A","B","C","D"};
range r=1.. ftoi(pow(2,card(s)));
{string} s2 [k in r] = {i | i in s: ((k div (ftoi(pow(2,(ord(s,i))))) mod 2) == 1)};
Line 1,285 ⟶ 2,635:
{
writeln(s2);
}
}</lang>{{out|which gives}}
</syntaxhighlight>
[{} {"A"} {"B"} {"A" "B"} {"C"} {"A" "C"} {"B" "C"} {"A" "B" "C"} {"D"} {"A"
 
which gives
 
<syntaxhighlight lang="result">
 
[{} {"A"} {"B"} {"A" "B"} {"C"} {"A" "C"} {"B" "C"} {"A" "B" "C"} {"D"} {"A"
"D"} {"B" "D"} {"A" "B" "D"} {"C" "D"} {"A" "C" "D"} {"B" "C" "D"}
{"A" "B" "C" "D"}]
</syntaxhighlight>
 
=={{header|Oz}}==
{{incomplete|Oz|It shows no proof of the cases with empty sets.}}Oz has a library for finite set constraints. Creating a power set is a trivial application of that:<lang oz>declare
<syntaxhighlight lang="oz">declare
%% Given a set as a list, returns its powerset (again as a list)
fun {Powerset Set}
Line 1,305 ⟶ 2,664:
end
in
{Inspect {Powerset [1 2 3 4]}}</langsyntaxhighlight>A more convential implementation without finite set constaints:
 
<lang oz>fun {Powerset2 Set}
A more convential implementation without finite set constaints:
<syntaxhighlight lang="oz">fun {Powerset2 Set}
case Set of nil then [nil]
[] H|T thens
Line 1,313 ⟶ 2,674:
{Append Acc {Map Acc fun {$ A} H|A end}}
end
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{incomplete|PARI/GP|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="parigp">vector(1<<#S,i,vecextract(S,i-1))</langsyntaxhighlight>
 
{{works with|PARI/GP|2.10.0+}}
The <code>forsubset</code> iterator was added in version 2.10.0 to efficiently iterate over combinations and power sets.
<syntaxhighlight lang="parigp">S=["a","b","c"]
forsubset(#S,s,print1(vecextract(S,s)" "))</syntaxhighlight>
{{out}}
<pre>[] ["a"] ["b"] ["c"] ["a", "b"] ["a", "c"] ["b", "c"] ["a", "b", "c"]</pre>
 
=={{header|Perl}}==
 
{{incomplete|Perl|It shows no proof of the cases with empty sets.}}Perl does not have a built-in set data-type. However, you can...
Perl does not have a built-in set data-type. However, you can...
<ul>
 
<li><p>'''''Use a third-party module'''''</p>
=== Module: [https://metacpan.org/pod/Algorithm::Combinatorics Algorithm::Combinatorics] ===
 
This module has an iterator over the power set. Note that it does not enforce that the input array is a set (no duplication). If each subset is processed immediately, this has an advantage of very low memory use.
<syntaxhighlight lang="perl">use Algorithm::Combinatorics "subsets";
my @S = ("a","b","c");
my @PS;
my $iter = subsets(\@S);
while (my $p = $iter->next) {
push @PS, "[@$p]"
}
say join(" ",@PS);</syntaxhighlight>
{{out}}
<pre>[a b c] [b c] [a c] [c] [a b] [b] [a] []</pre>
 
=== Module: [https://metacpan.org/pod/ntheory ntheory] ===
{{libheader|ntheory}}
The simplest solution is to use the one argument version of the combination iterator, which iterates over the power set.
<syntaxhighlight lang="perl">use ntheory "forcomb";
my @S = qw/a b c/;
forcomb { print "[@S[@_]] " } scalar(@S);
print "\n";</syntaxhighlight>
{{out}}
<pre>[] [a] [b] [c] [a b] [a c] [b c] [a b c]</pre>
 
Using the two argument version of the iterator gives a solution similar to the Raku and Python array versions.
<syntaxhighlight lang="perl">use ntheory "forcomb";
my @S = qw/a b c/;
for $k (0..@S) {
# Iterate over each $#S+1,$k combination.
forcomb { print "[@S[@_]] " } @S,$k;
}
print "\n";</syntaxhighlight>
{{out}}
<pre>[] [a] [b] [c] [a b] [a c] [b c] [a b c] </pre>
 
Similar to the Pari/GP solution, one can also use <tt>vecextract</tt> with an integer mask to select elements. Note that it does not enforce that the input array is a set (no duplication). This also has low memory if each subset is processed immediately and the range is applied with a loop rather than a map. A solution using <tt>vecreduce</tt> could be done identical to the array reduce solution shown later.
<syntaxhighlight lang="perl">use ntheory "vecextract";
my @S = qw/a b c/;
my @PS = map { "[".join(" ",vecextract(\@S,$_))."]" } 0..2**scalar(@S)-1;
say join(" ",@PS);</syntaxhighlight>
{{out}}
<pre>[] [a] [b] [a b] [c] [a c] [b c] [a b c]</pre>
 
=== Module: [https://metacpan.org/pod/Set::Object Set::Object] ===
 
The CPAN module [https://metacpan.org/pod/Set::Object Set::Object] provides a set implementation for sets of arbitrary objects, for which a powerset function could be defined and used like so:
 
<langsyntaxhighlight lang="perl">use Set::Object qw(set);
 
sub powerset {
Line 1,338 ⟶ 2,750:
my $powerset = powerset($set);
 
print $powerset->as_string, "\n";</langsyntaxhighlight>
 
{{out}}
Output:
<pre>Set::Object(Set::Object() Set::Object(1 2 3) Set::Object(1 2) Set::Object(1 3) Set::Object(1) Set::Object(2 3) Set::Object(2) Set::Object(3))</pre></li><li><p>'''''Use a simple custom hash-based set type'''''</p>
 
=== Simple custom hash-based set type ===
It's also easy to define a custom type for sets of strings or numbers, using a hash as the underlying representation (like the task description suggests):<lang perl>package Set {
 
It's also easy to define a custom type for sets of strings or numbers,
using a hash as the underlying representation (like the task description suggests):
 
<syntaxhighlight lang="perl">package Set {
sub new { bless { map {$_ => undef} @_[1..$#_] }, shift; }
sub elements { sort keys %{shift()} }
sub as_string { 'Set(' . join(' ', sort keys %{shift()}) . ')' }
# ...more set methods could be defined here...
}</syntaxhighlight>
}</lang>''(Note: For a ready-to-use module that uses this approach, and comes with all the standard set methods that you would expect, see the CPAN module [https://metacpan.org/pod/Set::Tiny Set::Tiny])''
 
''(Note: For a ready-to-use module that uses this approach, and comes with all the standard set methods that you would expect, see the CPAN module [https://metacpan.org/pod/Set::Tiny Set::Tiny])''
 
The limitation of this approach is that only primitive strings/numbers are allowed as hash keys in Perl, so a Set of Set's cannot be represented, and the return value of our powerset function will thus have to be a ''list'' of sets rather than being a Set object itself.
 
We could implement the function as an imperative foreach loop similar to the <code>Set::Object</code> based solution above, but using list folding (with the help of Perl's <code>List::Util</code> core module) seems a little more elegant in this case:<lang perl>use List::Util qw(reduce);
 
<syntaxhighlight lang="perl">use List::Util qw(reduce);
 
sub powerset {
Line 1,362 ⟶ 2,783:
my @subsets = powerset($set);
 
print $_->as_string, "\n" for @subsets;</langsyntaxhighlight>{{out}}<pre>Set()
 
{{out}}
<pre>
Set()
Set(1)
Set(2)
Line 1,369 ⟶ 2,794:
Set(1 3)
Set(2 3)
Set(1 2 3)
Set(1 2 3)</pre></li><li><p>'''''Use arrays'''''</p>If you don't actually need a proper set data-type that guarantees uniqueness of its elements, the simplest approach is to use arrays to store "sets" of items, in which case the implementation of the powerset function becomes quite short.
</pre>
 
=== Arrays ===
Recursive solution:<lang perl>sub powerset {
 
If you don't actually need a proper set data-type that guarantees uniqueness of its elements, the simplest approach is to use arrays to store "sets" of items, in which case the implementation of the powerset function becomes quite short.
 
Recursive solution:
<syntaxhighlight lang="perl">sub powerset {
@_ ? map { $_, [$_[0], @$_] } powerset(@_[1..$#_]) : [];
}</syntaxhighlight>
}</lang>List folding solution:<lang perl>use List::Util qw(reduce);
 
List folding solution:
 
<syntaxhighlight lang="perl">use List::Util qw(reduce);
 
sub powerset {
@{( reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_ )}
}</syntaxhighlight>
}</lang>{{out|Usage & output}}<lang perl>my @set = (1, 2, 3);
 
Usage & output:
<syntaxhighlight lang="perl">my @set = (1, 2, 3);
my @powerset = powerset(@set);
 
Line 1,384 ⟶ 2,822:
}
 
print set_to_string(@powerset), "\n";</langsyntaxhighlight>
{{out}}
{{}, {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}}</li></ul>
<pre>
=={{header|Perl 6}}==
{{}, {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}}
{{incomplete|Perl 6|It shows no proof of the cases with empty sets.}}{{works with|rakudo|2014-02-25}}<lang perl6>sub powerset(Set $s) { $s.combinations.map(*.Set).Set }
</pre>
say powerset set <a b c d>;</lang>{{out}}
 
<pre>set(set(), set(a), set(b), set(c), set(d), set(a, b), set(a, c), set(a, d), set(b, c), set(b, d), set(c, d), set(a, b, c), set(a, b, d), set(a, c, d), set(b, c, d), set(a, b, c, d))</pre>
=== Lazy evaluation ===
If you don't care about the actual <tt>Set</tt> type, the <tt>.combinations</tt> method by itself may be good enough for you:
If the initial set is quite large, constructing it's powerset all at once can consume lots of memory.
<lang perl6>.say for <a b c d>.combinations</lang>{{out}}<pre>&nbsp;
 
a
If you want to iterate through all of the elements of the powerset of a set, and don't mind each element being generated immediately before you process it, and being thrown away immediately after you're done with it, you can use vastly less memory. This is similar to the earlier solutions using the Algorithm::Combinatorics and ntheory modules.
b
 
c
The following algorithm uses one bit of memory for every element of the original set (technically it uses several bytes per element with current versions of Perl). This is essentially doing a <tt>vecextract</tt> operation by hand.
d
 
a b
<syntaxhighlight lang="perl">use strict;
a c
use warnings;
a d
sub powerset :prototype(&@) {
b c
my $callback = shift;
b d
my $bitmask = '';
c d
my $bytes = @_/8;
a b c
a b d {
my @indices = grep vec($bitmask, $_, 1), 0..$#_;
a c d
$callback->( @_[@indices] );
b c d
++vec($bitmask, $_, 8) and last for 0 .. $bytes;
a b c d</pre>
redo if @indices != @_;
}
}
 
print "powerset of empty set:\n";
powerset { print "[@_]\n" };
print "powerset of set {1,2,3,4}:\n";
powerset { print "[@_]\n" } 1..4;
my $i = 0;
powerset { ++$i } 1..9;
print "The powerset of a nine element set contains $i elements.\n";
</syntaxhighlight>
{{out}}
<pre>powerset of empty set:
[]
powerset of set {1,2,3,4}:
[]
[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]
The powerset of a nine element set contains 512 elements.
 
</pre>
The technique shown above will work with arbitrarily large sets, and uses a trivial amount of memory.
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">powerset</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">step</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pst</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000080;font-style:italic;">/*data*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000080;font-style:italic;">/*user_data*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">k</span><span style="color: #0000FF;"><</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">powerset</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">step</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">step</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">powerset</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">powerset</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">],</span><span style="color: #000000;">key</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">step</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">power_set</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">powerset</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">({},</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">dict_size</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)))</span>
<span style="color: #000000;">step</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"pst"</span><span style="color: #0000FF;">),</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">powerset</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">d1234</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">power_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d1234</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">d0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">power_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">({},</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d0</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">power_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d0</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{{},{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}}
{{}}
{{},{{}}}
</pre>
===alternative===
Adapted from the one I used on [[Ascending_primes#powerset]].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">power_set</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">powerset</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{}},</span> <span style="color: #000000;">subset</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{{},</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}}</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">subset</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">next</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">subset</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">sub</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">subset</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ni</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sub</span><span style="color: #0000FF;">),</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span>
<span style="color: #000000;">next</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">next</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">ni</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">powerset</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">powerset</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ni</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">subset</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">next</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">powerset</span><span style="color: #0000FF;">)=</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)))</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">powerset</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">power_set</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">power_set</span><span style="color: #0000FF;">({</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">power_set</span><span style="color: #0000FF;">({})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">power_set</span><span style="color: #0000FF;">({{}})</span>
<!--</syntaxhighlight>-->
{{out}}
Guaranteed to be in length order, and index order within each length.
<pre>
{{},{1},{2},{3},{4},{1,2},{1,3},{1,4},{2,3},{2,4},{3,4},{1,2,3},{1,2,4},{1,3,4},{2,3,4},{1,2,3,4}}
{{},{4},{3},{2},{1},{4,3},{4,2},{4,1},{3,2},{3,1},{2,1},{4,3,2},{4,3,1},{4,2,1},{3,2,1},{4,3,2,1}}
{{}}
{{},{{}}}
</pre>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
{{incomplete|PHP|It shows no proof of the cases with empty sets.}}
<lang PHP><?php
function get_subset($binary, $arr) {
// based on true/false values in $binary array, include/exclude
Line 1,467 ⟶ 3,016:
print_power_sets(array('singleton'));
print_power_sets(array('dog', 'c', 'b', 'a'));
?>
?></lang>{{out|Output in browser}}<pre>POWER SET of []
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
POWER SET of []
POWER SET of [singleton]
(empty)
Line 1,487 ⟶ 3,040:
a c dog
b c dog
a b c dog</pre>
</syntaxhighlight>
 
=={{header|PicoLisp}}==
{{incomplete|PicoLisp|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang PicoLisp="picolisp">(de powerset (Lst)
(ifn Lst
(cons)
Line 1,495 ⟶ 3,050:
(conc
(mapcar '((X) (cons (car Lst) X)) L)
L ) ) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
{{trans|REXX}}
{{incomplete|PL/I|It shows no proof of the cases with empty sets.}}<lang pli>*process source attributes xref or(!);
<syntaxhighlight lang="pli">*process source attributes xref or(!);
/*--------------------------------------------------------------------
* 06.01.2014 Walter Pachl translated from REXX
Line 1,562 ⟶ 3,119:
End;
 
End;</langsyntaxhighlight>
{{out}}<pre>{}
<pre>{}
{one}
{two}
Line 1,579 ⟶ 3,137:
{two,three,four}
{one,two,three,four}</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function power-set ($array) {
if($array) {
$n = $array.Count
function state($set, $i){
if($i -gt -1) {
state $set ($i-1)
state ($set+@($array[$i])) ($i-1)
} else {
"$($set | sort)"
}
}
$set = state @() ($n-1)
$power = 0..($set.Count-1) | foreach{@(0)}
$i = 0
$set | sort | foreach{$power[$i++] = $_.Split()}
$power | sort {$_.Count}
} else {@()}
 
}
$OFS = " "
$setA = power-set @(1,2,3,4)
"number of sets in setA: $($setA.Count)"
"sets in setA:"
$OFS = ", "
$setA | foreach{"{"+"$_"+"}"}
$setB = @()
"number of sets in setB: $($setB.Count)"
"sets in setB:"
$setB | foreach{"{"+"$_"+"}"}
$setC = @(@(), @(@()))
"number of sets in setC: $($setC.Count)"
"sets in setC:"
$setC | foreach{"{"+"$_"+"}"}
$OFS = " "
</syntaxhighlight>
<b>Output:</b>
<pre>
number of sets in setA: 16
sets in setA:
{}
{1}
{2}
{3}
{4}
{1, 2}
{1, 3}
{1, 4}
{2, 3}
{2, 4}
{3, 4}
{1, 2, 3}
{1, 2, 4}
{1, 3, 4}
{2, 3, 4}
{1, 2, 3, 4}
number of sets in setB: 0
sets in setB:
number of sets in setC: 2
sets in setC:
{}
{}
</pre>
 
=={{header|Prolog}}==
{{incomplete|Prolog|It shows no proof of the cases with empty sets.}}
===Logical (cut-free) Definition===
 
The predicate powerset(X,Y) defined here can be read as "Y is the
powerset of X", it being understood that lists are used to represent sets.
 
<p>The predicate subseq(X,Y) is true if and only if the list X is a subsequence of the list Y.</p>The definitions here are elementary, logical (cut-free), and efficient (within the class of comparably generic implementations).
The predicate subseq(X,Y) is true if and only if the list X is a subsequence of the list Y.
<lang Prolog>powerset(X,Y) :- bagof( S, subseq(S,X), Y).
 
The definitions here are elementary, logical (cut-free),
and efficient (within the class of comparably generic implementations).
<syntaxhighlight lang="prolog">powerset(X,Y) :- bagof( S, subseq(S,X), Y).
 
subseq( [], []).
subseq( [], [_|_]).
subseq( [X|Xs], [X|Ys] ) :- subseq(Xs, Ys).
subseq( [X|Xs], [_|Ys] ) :- append(_, [X|Zs], Ys), subseq(Xs, Zs).</lang>{{out}}<pre>?- powerset([1,2,3], X).
</syntaxhighlight>
{{out}}
<pre>?- powerset([1,2,3], X).
X = [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]].
 
Line 1,601 ⟶ 3,232:
X = 1,
Y = 2.</pre>
 
===Single-Functor Definition===
<langsyntaxhighlight Prologlang="prolog">power_set( [], [[]]).
power_set( [X|Xs], PS) :-
power_set(Xs, PS1),
maplist( append([X]), PS1, PS2 ), % i.e. prepend X to each PS1
append(PS1, PS2, PS).</langsyntaxhighlight>
{{out}}
{{out}}<pre>?- power_set([1,2,3,4,5,6,7,8], X), length(X,N), writeln(N).
<pre>?- power_set([1,2,3,4,5,6,7,8], X), length(X,N), writeln(N).
256</pre>
256
</pre>
 
===Constraint Handling Rules===
{{libheader|chr}}CHR is a programming language created by '''Professor Thom Frühwirth'''. Works with SWI-Prolog and module chr written by '''Tom Schrijvers''' and '''Jan Wielemaker'''.<lang Prologbr>:- use_module(library(chr)).
Works with SWI-Prolog and module chr written by '''Tom Schrijvers''' and '''Jan Wielemaker'''.
<syntaxhighlight lang="prolog">:- use_module(library(chr)).
 
:- chr_constraint chr_power_set/2, chr_power_set/1, clean/0.
Line 1,619 ⟶ 3,255:
 
only_one @ chr_power_set(A) \ chr_power_set(A) <=> true.
 
 
creation @ chr_power_set([H | T], A) <=>
Line 1,626 ⟶ 3,263:
chr_power_set(B).
 
 
empty_element @ chr_power_set([], _) <=> chr_power_set([]).</lang>{{out|Example of output}}<pre> ?- chr_power_set([1,2,3,4], []), findall(L, find_chr_constraint(chr_power_set(L)), LL), clean.
empty_element @ chr_power_set([], _) <=> chr_power_set([]).
LL = [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,4],[1,3],[1,3,4],[1,4],[2],[2,3],[2,3,4],[2,4],[3],[3,4],[4],[]] .</pre>
</syntaxhighlight>
{{out}}
<pre> ?- chr_power_set([1,2,3,4], []), findall(L, find_chr_constraint(chr_power_set(L)), LL), clean.
LL = [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,4],[1,3],[1,3,4],[1,4],[2],[2,3],[2,3,4],[2,4],[3],[3,4],[4],[]] .
</pre>
 
=={{header|PureBasic}}==
{{incomplete|PureBasic|It shows no proof of the cases with empty sets.}}This code is for console mode.<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
Define argc=CountProgramParameters()
If argc>=(SizeOf(Integer)*8) Or argc<1
Line 1,653 ⟶ 3,297:
PrintN("}")
EndIf
EndIf</syntaxhighlight>
EndIf</lang>{{out|Sample output}}
<!-- Output modified with a line break to avoid being too long -->
{{out}}
<pre>C:\Users\PureBasic_User\Desktop>"Power Set.exe" 1 2 3 4
{{}, {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}}</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">def list_powerset(lst):
{{incomplete|Python|It shows no proof of the cases with empty sets.}}
<lang python>def list_powerset(lst):
# the power set of the empty set has one element, the empty set
result = [[]]
Line 1,678 ⟶ 3,324:
 
def powerset(s):
return frozenset(map(frozenset, list_powerset(list(s))))</syntaxhighlight>
return frozenset(map(frozenset, list_powerset(list(s))))</lang><tt>list_powerset</tt> computes the power set of a list of distinct elements. <tt>powerset</tt> simply converts the input and output from lists to sets. We use the <tt>frozenset</tt> type here for immutable sets, because unlike mutable sets, it can be put into other sets.
 
{{out|Example}}<pre>
<tt>list_powerset</tt> computes the power set of a list of distinct elements. <tt>powerset</tt> simply converts the input and output from lists to sets. We use the <tt>frozenset</tt> type here for immutable sets, because unlike mutable sets, it can be put into other sets.
 
{{out|Example}}
<pre>
>>> list_powerset([1,2,3])
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Line 1,685 ⟶ 3,335:
frozenset([frozenset([3]), frozenset([1, 2]), frozenset([]), frozenset([2, 3]), frozenset([1]), frozenset([1, 3]), frozenset([1, 2, 3]), frozenset([2])])
</pre>
 
==== Further Explanation ====
If you take out the requirement to produce sets and produce list versions of each powerset element, then add a print to trace the execution, you get this simplified version of the program above where it is easier to trace the inner workings<lang python>def powersetlist(s):
<syntaxhighlight lang="python">def powersetlist(s):
r = [[]]
for e in s:
Line 1,694 ⟶ 3,346:
 
s= [0,1,2,3]
print "\npowersetlist(%r) =\n %r" % (s, powersetlist(s))</langsyntaxhighlight>{{out|Sample output}}
 
r: [[]] e: 0
{{out}}
r: [[], [0]] e: 1
<pre>r: [[], [0], [1], [0, 1]] e: 20
r: [[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2]] e: 31
r: [[], [0], [1], [0, 1]] e: 2
r: [[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2]] e: 3
powersetlist([0, 1, 2, 3]) =
 
powersetlist([0, 1, 2, 3]) =
[[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2], [3], [0, 3], [1, 3], [0, 1, 3], [2, 3], [0, 2, 3], [1, 2, 3], [0, 1, 2, 3]]
</pre>
 
=== Binary Count method ===
If you list the members of the set and include them according to if the corresponding bit position of a binary count is true then you generate the powerset.
(Note that only frozensets can be members of a set in the second function)<lang python>def powersequence(val):
<syntaxhighlight lang="python">def powersequence(val):
''' Generate a 'powerset' for sequence types that are indexable by integers.
Uses a binary count to enumerate the members and returns a list
Line 1,729 ⟶ 3,385:
set([frozenset([7]), frozenset([8, 6, 7]), frozenset([6]), frozenset([6, 7]), frozenset([]), frozenset([8]), frozenset([8, 7]), frozenset([8, 6])])
'''
return set( frozenset(x) for x in powersequence(list(s)) )</langsyntaxhighlight>
 
=== Recursive Alternative ===
This is an (inefficient) recursive version that almost reflects the recursive definition of a power set as explained in http://en.wikipedia.org/wiki/Power_set#Algorithms. It does not create a sorted output.<lang python>def p(l):
 
<syntaxhighlight lang="python">
def p(l):
if not l: return [[]]
return p(l[1:]) + [[l[0]] + x for x in p(l[1:])]</lang>
</syntaxhighlight>
 
===Python: Standard documentation===
Pythons [http://docs.python.org/3/library/itertools.html?highlight=powerset#itertools-recipes documentation] has a method that produces the groupings, but not as sets:<lang python>>>> from pprint import pprint as pp
 
<syntaxhighlight lang="python">>>> from pprint import pprint as pp
>>> from itertools import chain, combinations
>>>
Line 1,760 ⟶ 3,424:
(3, 4),
(4,)}
>>> </langsyntaxhighlight>
 
=={{header|Qi}}==
{{trans|Scheme}}
{{incomplete|Qi|It shows no proof of the cases with empty sets.}}{{trans|Scheme}}<lang qi>(define powerset
<syntaxhighlight lang="qi">
(define powerset
[] -> [[]]
[A|As] -> (append (map (cons A) (powerset As))
(powerset As)))</lang>
</syntaxhighlight>
 
=={{header|Quackery}}==
 
Quackery is, when seen from a certain perspective, an assembly language that recognises
only three types, "operators", which correspond to op-codes, "numbers" i.e. bignums, and
"nests" which are ordered sequences of zero of more operator, bignums and nests. Everything
else is a matter of interpretation.
 
Integers can be used as a set of natural numbers, with (in binary) 0 corresponding to the
empty set, 1 corresponding to the set of the natural number 1, 10 corresponding to the set
of the natural number 2, 11 corresponding to the set of the natural numbers 1 and 2, and so
on. With this sort of set, enumerating the powerset of the numbers 0 to 4, for example
simply consists of enumerating the numbers 0 to 15 inclusive. Operations on this sort of
set, such as union and intersection, correspond to bitwise logic operators.
 
The other way of implementing sets is with nests, with each item in a nest corresponding
to an item in the set. This is computationally slower and more complex to code, but has the
advantage that it permits sets of sets, which are required for this task.
 
<syntaxhighlight lang="quackery"> [ stack ] is (ps).stack
[ stack ] is (ps).items
[ stack ] is (ps).result
[ 1 - (ps).items put
0 (ps).stack put
[] (ps).result put
[ (ps).result take
(ps).stack behead
drop nested join
(ps).result put
(ps).stack take
dup (ps).items share
= iff
[ drop
(ps).stack size 1 > iff
[ 1 (ps).stack tally ] ]
else
[ dup (ps).stack put
1+ (ps).stack put ]
(ps).stack size 1 = until ]
(ps).items release
(ps).result take ] is (ps) ( n --> )
 
[ dup size dip
[ witheach
[ over swap peek swap ] ]
nip pack ] is arrange ( [ [ --> [ )
 
[ dup [] = iff
nested done
dup size (ps)
' [ [ ] ] swap join
[] unrot witheach
[ dip dup arrange
nested
rot swap join swap ]
drop ] is powerset ( [ --> [ )
 
' [ [ 1 2 3 4 ] [ ] [ [ ] ] ]
witheach
[ say "The powerset of "
dup echo cr
powerset witheach [ echo cr ]
cr ]</syntaxhighlight>
 
{{out}}
 
<pre>The powerset of [ 1 2 3 4 ]
[ ]
[ 1 ]
[ 1 2 ]
[ 1 2 3 ]
[ 1 2 3 4 ]
[ 1 2 4 ]
[ 1 3 ]
[ 1 3 4 ]
[ 1 4 ]
[ 2 ]
[ 2 3 ]
[ 2 3 4 ]
[ 2 4 ]
[ 3 ]
[ 3 4 ]
[ 4 ]
 
The powerset of [ ]
[ ]
 
The powerset of [ [ ] ]
[ ]
[ [ ] ]
</pre>
 
=={{header|R}}==
{{incomplete|R|It shows no proof of the cases with empty sets.}}
===Non-recursive version===
The conceptual basis for this algorithm is the following:<lang>for each element in the set:
<syntaxhighlight lang="text">for each element in the set:
for each subset constructed so far:
new subset = (subset + element)</lang>This method is much faster than a recursive method, though the speed is still O(2^n).<lang R>powerset = function(set){
</syntaxhighlight>
ps = list()
 
ps[[1]] = numeric() #Start with the empty set.
This method is much faster than a recursive method, though the speed is still O(2^n).
 
<syntaxhighlight lang="r">powerset <- function(set){
ps <- list()
ps[[1]] <- numeric() #Start with the empty set.
for(element in set){ #For each element in the set, take all subsets
temp =<- vector(mode="list",length=length(ps)) #currently in "ps" and create new subsets (in "temp")
for(subset in 1:length(ps)){ #by adding "element" to each of them.
temp[[subset]] = c(ps[[subset]],element)
}
ps= <- c(ps,temp) #Add the additional subsets ("temp") to "ps".
}
return(ps)
}
 
powerset(1:4)
powerset(1:4)</lang>The list "temp" is a compromise between the speed costs of doing arithmetic and of creating new lists (since R lists are immutable, appending to a list means actually creating a new list object). Thus, "temp" collects new subsets that are later added to the power set. This improves the speed by 4x compared to extending the list "ps" at every step.
</syntaxhighlight>
 
The list "temp" is a compromise between the speed costs of doing
arithmetic and of creating new lists (since R lists are immutable,
appending to a list means actually creating a new list object).
Thus, "temp" collects new subsets that are later added to the power set.
This improves the speed by 4x compared to extending the list "ps" at every step.
 
===Recursive version===
{{libheader|sets}}
The sets package includes a recursive method to calculate the power set. However, this method takes ~100 times longer than the non-recursive method above.<lang R>library(sets)</lang>
However, this method takes ~100 times longer than the non-recursive method above.
An example with a vector.<lang R>v <- (1:3)^2
<syntaxhighlight lang="r">library(sets)</syntaxhighlight>
An example with a vector.
<syntaxhighlight lang="r">v <- (1:3)^2
sv <- as.set(v)
2^sv</langsyntaxhighlight>
{{}, {1}, {4}, {9}, {1, 4}, {1, 9}, {4, 9}, {1, 4, 9}}
An example with a list.<lang R>l <- list(a=1, b="qwerty", c=list(d=TRUE, e=1:3))
<syntaxhighlight lang="r">l <- list(a=1, b="qwerty", c=list(d=TRUE, e=1:3))
sl <- as.set(l)
2^sl</langsyntaxhighlight>
{{}, {1}, {"qwerty"}, {<<list(2)>>}, {1, <<list(2)>>}, {"qwerty",
1}, {"qwerty", <<list(2)>>}, {"qwerty", 1, <<list(2)>>}}
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
{{incomplete|Racket|It shows no proof of the cases with empty sets.}}<lang racket>;;; Direct translation of 'functional' ruby method
;;; Direct translation of 'functional' ruby method
(define (powerset s)
(for/fold ([outer-set (set(set))]) ([element s])
(set-union outer-set
(list->set (set-map outer-set
(λ(inner-set) (set-add inner-set element)))))))</lang>
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2014-02-25}}
<syntaxhighlight lang="raku" line>sub powerset(Set $s) { $s.combinations.map(*.Set).Set }
say powerset set <a b c d>;</syntaxhighlight>
{{out}}
<pre>set(set(), set(a), set(b), set(c), set(d), set(a, b), set(a, c), set(a, d), set(b, c), set(b, d), set(c, d), set(a, b, c), set(a, b, d), set(a, c, d), set(b, c, d), set(a, b, c, d))</pre>
If you don't care about the actual <tt>Set</tt> type, the <tt>.combinations</tt> method by itself may be good enough for you:
<syntaxhighlight lang="raku" line>.say for <a b c d>.combinations</syntaxhighlight>
{{out}}
<pre>&nbsp;
a
b
c
d
a b
a c
a d
b c
b d
c d
a b c
a b d
a c d
b c d
a b c d</pre>
 
=={{header|Rascal}}==
<syntaxhighlight lang="rascal">
{{incomplete|Rascal|It shows no proof of the cases with empty sets.}}
<lang rascal>import Set;
 
public set[set[&T]] PowerSet(set[&T] s) = power(s);</lang>{{out|An example output}}
</syntaxhighlight>
rascal>PowerSet({1,2,3,4})
{{out}}
set[set[int]]: {
<syntaxhighlight lang="rascal">
rascal>PowerSet({1,2,3,4})
set[set[int]]: {
{4,3},
{4,2,1},
Line 1,827 ⟶ 3,639:
{3,2,1},
{}
}
</syntaxhighlight>
 
=={{header|REXX}}==
{{incomplete|REXX|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="rexx">/*REXX program to displaydisplays a power set,; items may be anything (nobut can't have blanks).*/
parseParse Arg text arg S /*letallow the user specify theoptional set. */
ifIf Stext='' Then then S='one two three four' /*NoneNot specified? UseThen use the default.*/
text='one two three four'
N=words(S) /*number of items in the list.*/
n=words(text)
ps='{}' /*start with a null power set.*/
psi=0
do chunk=1 for N /*traipse through the items. */
Do k=0 To n ps=ps combN(N,chunk) /* loops from 0 to /*Nn elements items,of a CHUNKset at a time. */
cc=comb(n,k) end/* returns the combinations of 1 through k /*chunk*/
Do while pos('/',cc)>0 /* as long as there is a combination */
w=words(ps)
Parse Var cc elist '/' cc /* get doi k=1from comb's forresult wstring /*show combinations, one/line.*/
psl='' /* initialize the list of words */
say right(k,length(w)) word(ps,k)
psi=psi+1 end /*k index of this set */
exit Do While elist<>'' /* loop through elements /*stick a fork in it, we done.*/
parse var elist e elist /* get an element (a digit) */
/*─────────────────────────────────────$COMBN subroutine────────────────*/
psl=psl','word(text,e) /* add corresponding test word to set */
combN: procedure expose $ S; parse arg x,y; $=
End
!.=0; base=x+1; bbase=base-y; ym=y-1; do p=1 for y; !.p=p; end
psl=substr(psl,2) /* doget j=1;rid L=of leading comma */
Say right(psi,2) '{'psl'}' /* show this element of the power set */
do d=1 for y; _=!.d; L=L','word(S,_); end
End
$=$ '{'strip(L,'L',",")'}'
End
!.y=!.y+1; if !.y==base then if .combU(ym) then leave
Exit
end /*j*/
comb: Procedure
return strip($) /*return with partial powerset*/
/***********************************************************************
* Returns the combinations of size digits out of things digits
* e.g. comb(4,2) -> ' 1 2/1 3/1 4/2 3/2 4/3 4/'
1 2/ 1 3/ 1 4/ 2 3/ 2 4/ 3 4 /
***********************************************************************/
Parse Arg things,size
n=2**things-1
list=''
Do u=1 To n
co=combinations(u)
If co>'' Then
list=list '/' combinations(u)
End
Return substr(space(list),2) '/' /* remove leading / */
 
combinations: Procedure Expose things size
.combU: procedure expose !. y bbase; parse arg d; if d==0 then return 1
Parse Arg u
p=!.d; do u=d to y; !.u=p+1
nc=0
if !.u==bbase+u then return .combU(u-1)
bu=x2b(d2x(u))
p=!.u
bu1=space(translate(bu,' ',0),0)
end /*u*/
If length(bu1)=size Then Do
return 0</lang>
ub=reverse(bu)
{{out|when using the default input}}
res=''
<pre> 1 {}
Do i=1 To things
c=i
If substr(ub,i,1)=1 Then res=res i
End
Return res
End
Else
Return ''</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
1 {}
2 {one}
3 {two}
Line 1,874 ⟶ 3,713:
14 {one,three,four}
15 {two,three,four}
16 {one,two,three,four}</pre>
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Power set
 
list = ["1", "2", "3", "4"]
see powerset(list)
func powerset(list)
s = "{"
for i = 1 to (2 << len(list)) - 1 step 2
s = s + "{"
for j = 1 to len(list)
if i & (1 << j)
s = s + list[j] + ","
ok
next
if right(s,1) = ","
s = left(s,len(s)-1)
ok
s = s + "},"
next
return left(s,len(s)-1) + "}"
</syntaxhighlight>
Output:
<pre>
{{},{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}}
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.8}}
{| class="wikitable"
! RPL code
! Comment
|-
|
'''IF''' DUP SIZE
'''THEN''' LAST OVER SWAP GET → last
≪ LIST→ 1 - SWAP DROP →LIST '''POWST'''
1 OVER SIZE '''FOR''' j
DUP j GET last + 1 →LIST + '''NEXT'''
'''ELSE''' 1 →LIST '''END'''
≫ ''''POWST'''' STO
|
'''POWST''' ''( { set } -- { power set } )''
if set is not empty
then store last item
get power set of ''{ set } - last item''
for all sets of ''{ set } - last item'' power set
add last item to set, then set to power set
else return { { } }
|}
{ 1 2 3 4 } '''POWST'''
{ } '''POWST'''
 
{{out}}
<pre>
2: { { } { 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 } }
1: { { } }
</pre>
 
=={{header|Ruby}}==
{{incomplete|Ruby|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="ruby"># Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
# See the link if you want a shorter version. This was intended to show the reader how the method works.
# This was intended to show the reader how the method works.
class Array
# Adds a power_set method to every array, i.e.: [1, 2].power_set
Line 1,918 ⟶ 3,824:
p %w(one two three).func_power_set
 
p Set[1,2,3].powerset</lang>{{out}}<presyntaxhighlight>
{{out}}
<pre>
[[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], [1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]
[[], ["one"], ["two"], ["one", "two"], ["three"], ["one", "three"], ["two", "three"], ["one", "two", "three"]]
#<Set: {#<Set: {}>, #<Set: {1}>, #<Set: {2}>, #<Set: {1, 2}>, #<Set: {3}>, #<Set: {1, 3}>, #<Set: {2, 3}>, #<Set: {1, 2, 3}>}>
</pre>
 
=={{header|Rust}}==
This implementation consumes the input set, requires that the type <b>T</b> has a full order a.k.a implements the <b>Ord</b> trait and that <b>T</b> is clonable.
 
<syntaxhighlight lang="rust">use std::collections::BTreeSet;
 
fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> {
if set.is_empty() {
let mut powerset = BTreeSet::new();
powerset.insert(set);
return powerset;
}
// Access the first value. This could be replaced with `set.pop_first().unwrap()`
// But this is an unstable feature
let entry = set.iter().nth(0).unwrap().clone();
set.remove(&entry);
let mut powerset = powerset(set);
for mut set in powerset.clone().into_iter() {
set.insert(entry.clone());
powerset.insert(set);
}
powerset
}
 
fn main() {
let set = (1..5).collect();
let set = powerset(set);
println!("{:?}", set);
 
let set = ["a", "b", "c", "d"].iter().collect();
let set = powerset(set);
println!("{:?}", set);
}
</syntaxhighlight>
 
{{out}}
<pre>
{{}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 4}, {1, 3}, {1, 3, 4}, {1, 4}, {2}, {2, 3}, {2, 3, 4}, {2, 4}, {3}, {3, 4}, {4}}
{{}, {"a"}, {"a", "b"}, {"a", "b", "c"}, {"a", "b", "c", "d"}, {"a", "b", "d"}, {"a", "c"}, {"a", "c", "d"}, {"a", "d"}, {"b"}, {"b", "c"}, {"b", "c", "d"}, {"b", "d"}, {"c"}, {"c", "d"}, {"d"}}
 
</pre>
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
{{incomplete|SAS|It shows no proof of the cases with empty sets.}}<lang SAS>options mprint mlogic symbolgen source source2;
options mprint mlogic symbolgen source source2;
 
%macro SubSets (FieldCount = );
Line 1,976 ⟶ 3,927:
 
%end;
%Mend SubSets;</lang>You can then call the macro as:
</syntaxhighlight>
<lang SAS>%SubSets(FieldCount = 5);</lang>The output will be the dataset SUBSETS and will have a 5 columns F1, F2, F3, F4, F5 and 32 columns, one with each combination of 1 and missing values.{{out}}<pre>
 
You can then call the macro as:
<syntaxhighlight lang="sas">
%SubSets(FieldCount = 5);
</syntaxhighlight>
 
The output will be the dataset SUBSETS
and will have a 5 columns F1, F2, F3, F4, F5 and 32 columns,
one with each combination of 1 and missing values.
 
{{out}}
<pre>
Obs F1 F2 F3 F4 F5 RowCount
1 . . . . . 1
Line 2,010 ⟶ 3,973:
30 1 1 1 . 1 30
31 1 1 1 1 . 31
32 1 1 1 1 1 32</pre>
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">import scala.compat.Platform.currentTime
[[Category:Scala Implementations]]
Testing the cases:
#{1,2,3,4}
#<math>\mathcal{P}</math>(<math>\varnothing</math>) = { <math>\varnothing</math> }
#<math>\mathcal{P}</math>({<math>\varnothing</math>}) = { <math>\varnothing</math>, { <math>\varnothing</math> } }
<lang scala>import scala.compat.Platform.currentTime
 
object Powerset extends App {
Line 2,024 ⟶ 3,984:
assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4),
Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4)))
assert(powerset(Set()) == Set(Set()))
assert(powerset(Set(Set())) == Set(Set(), Set(Set())))
 
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}</syntaxhighlight>
}</lang>Another option that produces a iterator of the sets:<lang scala>def powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet)</lang>
 
Another option that produces lazy sequence of the sets:
<syntaxhighlight lang="scala">def powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet)</syntaxhighlight>
 
A tail-recursive version:
<syntaxhighlight lang="scala">def powerset[A](s: Set[A]) = {
def powerset_rec(acc: List[Set[A]], remaining: List[A]): List[Set[A]] = remaining match {
case Nil => acc
case head :: tail => powerset_rec(acc ++ acc.map(_ + head), tail)
}
powerset_rec(List(Set.empty[A]), s.toList)
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{incomplete|Scheme|It shows no proof of the cases with empty sets.}}{{trans|Common Lisp}}
<langsyntaxhighlight lang="scheme">(define (power-set set)
(if (null? set)
'(())
Line 2,043 ⟶ 4,013:
 
(display (power-set (list "A" "C" "E")))
(newline)</langsyntaxhighlight>{{out}}
{{out}}
((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) ())
((A C E) (A C) (A E) (A) (C E) (C) (E) ())
 
Call/cc generation:<lang lisp>(define (power-set lst)
Call/cc generation:<syntaxhighlight lang="lisp">(define (power-set lst)
(define (iter yield)
(let recur ((a '()) (b lst))
Line 2,068 ⟶ 4,040:
(display a)
(newline)
(loop (x)))))</langsyntaxhighlight>output<lang>(1 2)
{{out}}
<pre>(1 2)
(1 3)
(1)
Line 2,074 ⟶ 4,048:
(2)
(3)
()</pre>
()</lang>Iterative:<lang scheme>(define (power_set_iter set)
 
Iterative:<syntaxhighlight lang="scheme">
(define (power_set_iter set)
(let loop ((res '(())) (s set))
(if (empty? s)
res
(loop (append (map (lambda (i) (cons (car s) i)) res) res) (cdr s)))))
</syntaxhighlight>
</lang>{{out}} '((e d c b a)
 
{{out}}
<pre>
'((e d c b a)
(e d c b)
(e d c a)
Line 2,111 ⟶ 4,092:
(a)
())
</pre>
 
=={{header|Seed7}}==
{{incomplete|Seed7|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="seed7">$ include "seed7_05.s7i";
const func array bitset: powerSet (in bitset: baseSet) is func
Line 2,140 ⟶ 4,123:
writeln(aSet);
end for;
end func;</langsyntaxhighlight>{{out}}<pre>{}
 
{{out}}
<pre>
{}
{1}
{2}
Line 2,155 ⟶ 4,142:
{1, 3, 4}
{2, 3, 4}
{1, 2, 3, 4}</pre>
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="haskell">Pfour := pow({1, 2, 3, 4});
Pempty := pow({});
PPempty := pow(Pempty);
 
print(Pfour);
print(Pempty);
print(PPempty);</syntaxhighlight>
 
{{out}}
<pre>{{} {1} {2} {3} {4} {1 2} {1 3} {1 4} {2 3} {2 4} {3 4} {1 2 3} {1 2 4} {1 3 4} {2 3 4} {1 2 3 4}}
{{}}
{{} {{}}}</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var arr = %w(a b c)
for i in (0 .. arr.len) {
say arr.combinations(i)
}</syntaxhighlight>
 
{{out}}
<pre>
[[]]
[["a"], ["b"], ["c"]]
[["a", "b"], ["a", "c"], ["b", "c"]]
[["a", "b", "c"]]
</pre>
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">SIMSET
BEGIN
 
LINK CLASS LOF_INT(N); INTEGER N;;
 
LINK CLASS LOF_LOF_INT(H); REF(HEAD) H;;
 
REF(HEAD) PROCEDURE MAP(P_LI, P_LLI);
REF(HEAD) P_LI;
REF(HEAD) P_LLI;
BEGIN
REF(HEAD) V_RESULT;
V_RESULT :- NEW HEAD;
IF NOT P_LLI.EMPTY THEN BEGIN
REF(LOF_LOF_INT) V_LLI;
V_LLI :- P_LLI.FIRST QUA LOF_LOF_INT;
WHILE V_LLI =/= NONE DO BEGIN
REF(HEAD) V_NEWLIST;
V_NEWLIST :- NEW HEAD;
! ADD THE SAME 1ST ELEMENT TO EVERY NEWLIST ;
NEW LOF_INT(P_LI.FIRST QUA LOF_INT.N).INTO(V_NEWLIST);
IF NOT V_LLI.H.EMPTY THEN BEGIN
REF(LOF_INT) V_LI;
V_LI :- V_LLI.H.FIRST QUA LOF_INT;
WHILE V_LI =/= NONE DO BEGIN
NEW LOF_INT(V_LI.N).INTO(V_NEWLIST);
V_LI :- V_LI.SUC;
END;
END;
NEW LOF_LOF_INT(V_NEWLIST).INTO(V_RESULT);
V_LLI :- V_LLI.SUC;
END;
END;
MAP :- V_RESULT;
END MAP;
 
REF(HEAD) PROCEDURE SUBSETS(P_LI);
REF(HEAD) P_LI;
BEGIN
REF(HEAD) V_RESULT;
IF P_LI.EMPTY THEN BEGIN
V_RESULT :- NEW HEAD;
NEW LOF_LOF_INT(NEW HEAD).INTO(V_RESULT);
END ELSE BEGIN
REF(HEAD) V_SUBSET, V_MAP;
REF(LOF_INT) V_LI;
V_SUBSET :- NEW HEAD;
V_LI :- P_LI.FIRST QUA LOF_INT;
! SKIP OVER 1ST ELEMENT ;
IF V_LI =/= NONE THEN V_LI :- V_LI.SUC;
WHILE V_LI =/= NONE DO BEGIN
NEW LOF_INT(V_LI.N).INTO(V_SUBSET);
V_LI :- V_LI.SUC;
END;
V_RESULT :- SUBSETS(V_SUBSET);
V_MAP :- MAP(P_LI, V_RESULT);
IF NOT V_MAP.EMPTY THEN BEGIN
REF(LOF_LOF_INT) V_LLI;
V_LLI :- V_MAP.FIRST QUA LOF_LOF_INT;
WHILE V_LLI =/= NONE DO BEGIN
NEW LOF_LOF_INT(V_LLI.H).INTO(V_RESULT);
V_LLI :- V_LLI.SUC;
END;
END;
END;
SUBSETS :- V_RESULT;
END SUBSETS;
 
PROCEDURE PRINT_LIST(P_LI); REF(HEAD) P_LI;
BEGIN
OUTTEXT("[");
IF NOT P_LI.EMPTY THEN BEGIN
INTEGER I;
REF(LOF_INT) V_LI;
I := 0;
V_LI :- P_LI.FIRST QUA LOF_INT;
WHILE V_LI =/= NONE DO BEGIN
IF I > 0 THEN OUTTEXT(",");
OUTINT(V_LI.N, 0);
V_LI :- V_LI.SUC;
I := I+1;
END;
END;
OUTTEXT("]");
END PRINT_LIST;
 
PROCEDURE PRINT_LIST_LIST(P_LLI); REF(HEAD) P_LLI;
BEGIN
OUTTEXT("[");
IF NOT P_LLI.EMPTY THEN BEGIN
INTEGER I;
REF(LOF_LOF_INT) V_LLI;
I := 0;
V_LLI :- P_LLI.FIRST QUA LOF_LOF_INT;
WHILE V_LLI =/= NONE DO BEGIN
IF I > 0 THEN BEGIN
OUTTEXT(",");
! OUTIMAGE;
END;
PRINT_LIST(V_LLI.H);
V_LLI :- V_LLI.SUC;
I := I+1;
END;
END;
OUTTEXT("]");
OUTIMAGE;
END PRINT_LIST_LIST;
 
INTEGER N;
REF(HEAD) V_RANGE;
REF(HEAD) V_LISTS;
 
V_RANGE :- NEW HEAD;
V_LISTS :- SUBSETS(V_RANGE);
PRINT_LIST_LIST(V_LISTS);
OUTIMAGE;
FOR N := 1 STEP 1 UNTIL 4 DO BEGIN
NEW LOF_INT(N).INTO(V_RANGE);
V_LISTS :- SUBSETS(V_RANGE);
PRINT_LIST_LIST(V_LISTS);
OUTIMAGE;
END;
END.
</syntaxhighlight>
{{out}}
<pre>
[[]]
 
[[],[1]]
 
[[],[2],[1],[1,2]]
 
[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
 
[[],[4],[3],[3,4],[2],[2,4],[2,3],[2,3,4],[1],[1,4],[1,3],[1,3,4],[1,2],[1,2,4],
[1,2,3],[1,2,3,4]]
</pre>
 
=={{header|Smalltalk}}==
{{incomplete|Smalltalk|It shows no proof of the cases with empty sets.}}
{{works with|GNU Smalltalk}}
Code from [http://smalltalk.gnu.org/blog/bonzinip/fun-generators Bonzini's blog]<lang smalltalk>Collection extend [
 
<syntaxhighlight lang="smalltalk">Collection extend [
power [
^(0 to: (1 bitShift: self size) - 1) readStream collect: [ :each || i |
Line 2,165 ⟶ 4,322:
self select: [ :elem | (each bitAt: (i := i + 1)) = 1 ] ]
]
].</syntaxhighlight>
].</lang><lang smalltalk>#(1 2 4) power do: [ :each |
 
<syntaxhighlight lang="smalltalk">#(1 2 4) power do: [ :each |
each asArray printNl ].
 
#( 'A' 'C' 'E' ) power do: [ :each |
each asArray printNl ].</langsyntaxhighlight>
 
=={{header|Standard ML}}==
 
{{incomplete|Standard ML|It shows no proof of the cases with empty sets.}}Version for lists:<lang sml>fun subsets xs = foldr (fn (x, rest) => rest @ map (fn ys => x::ys) rest) [[]] xs</lang>
version for lists:
<syntaxhighlight lang="sml">fun subsets xs = foldr (fn (x, rest) => rest @ map (fn ys => x::ys) rest) [[]] xs</syntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|Revision 4 - tested with Xcode 9.2 playground}}
 
<syntaxhighlight lang="swift">func powersetFrom<T>(_ elements: Set<T>) -> Set<Set<T>> {
guard elements.count > 0 else {
return [[]]
}
var powerset: Set<Set<T>> = [[]]
for element in elements {
for subset in powerset {
powerset.insert(subset.union([element]))
}
}
return powerset
}
 
// Example:
powersetFrom([1, 2, 4])</syntaxhighlight>
{{out}}
<pre>{
{2, 4}
{4, 1}
{4},
{2, 4, 1}
{2, 1}
Set([])
{1}
{2}
}</pre>
 
<syntaxhighlight lang="swift">//Example:
powersetFrom(["a", "b", "d"])</syntaxhighlight>
{{out}}
<pre>{
{"b", "d"}
{"b"}
{"d"},
{"a"}
{"b", "d", "a"}
Set([])
{"d", "a"}
{"b", "a"}
}</pre>
 
=={{header|Tcl}}==
{{incomplete|Tcl|It<syntaxhighlight shows no proof of the cases with empty sets.}}<lang ="tcl">proc subsets {l} {
set res [list [list]]
foreach e $l {
Line 2,180 ⟶ 4,387:
return $res
}
puts [subsets {a b c d}]</langsyntaxhighlight>{{out}}
{{out}}
{} a b {a b} c {a c} {b c} {a b c} d {a d} {b d} {a b d} {c d} {a c d} {b c d} {a b c d}
<pre>{} a b {a b} c {a c} {b c} {a b c} d {a d} {b d} {a b d} {c d} {a c d} {b c d} {a b c d}</pre>
===Binary Count Method===
<langsyntaxhighlight lang="tcl">proc powersetb set {
set res {}
for {set i 0} {$i < 2**[llength $set]} {incr i} {
Line 2,194 ⟶ 4,402:
}
return $res
}</langsyntaxhighlight>
 
=={{header|TXR}}==
 
{{incomplete|TXR|It shows no proof of the cases with empty sets.}}
{{trans|Common Lisp}}The power set function can be written concisely like this:<lang txr>(defun power-set (s)
 
(reduce-right
<syntaxhighlight lang="txr">(defun power-set (s)
(op append (mapcar (op cons @@1) @2) @2)
(mappend* (op comb s) (range 0 (length s))))</syntaxhighlight>
s '(())))</lang>A complete program which takes command line arguments and prints the power set in comma-separated brace notation:<lang txr>@(do (defun power-set (s)
 
(reduce-right
This generates the lists of combinations of all possible lengths, from 0 to the length of <code>s</code> and catenates them. The <code>comb</code> function generates a lazy list, so it is appropriate to use <code>mappend*</code> (the lazy version of <code>mappend</code>) to keep the behavior lazy.
(op append (mapcar (op cons @@1) @2) @2)
 
s '(()))))
A complete program which takes command line arguments and prints the power set in comma-separated brace notation:
 
<syntaxhighlight lang="txr">@(do (defun power-set (s)
(mappend* (op comb s) (range 0 (length s)))))
@(bind pset @(power-set *args*))
@(output)
Line 2,209 ⟶ 4,422:
{@(rep)@pset, @(last)@pset@(empty)@(end)}
@ (end)
@(end)</syntaxhighlight>
@(end)</lang><pre>$ txr rosetta/power-set.txr 1 2 3
{{out}}
<pre>$ txr rosetta/power-set.txr 1 2 3
{1, 2, 3}
{1, 2}
Line 2,217 ⟶ 4,432:
{2}
{3}
{}</pre>
{}</pre>What is not obvious is that the above <code>power-set</code> function generalizes to strings and vectors.<lang txr>@(do (defun power-set (s)
 
(reduce-right
The above <code>power-set</code> function
(op append (mapcar (op cons @@1) @2) @2)
generalizes to strings and vectors.
s '(())))
 
<syntaxhighlight lang="txr">@(do (defun power-set (s)
(mappend* (op comb s) (range 0 (length s))))
(prinl (power-set "abc"))
(prinl (power-set "b"))
(prinl (power-set ""))
(prinl (power-set #(1 2 3))))</langsyntaxhighlight>txr power-set-generic.txr
{{out}}
((#\a #\b #\c) (#\a #\b) (#\a #\c) (#\a) (#\b #\c) (#\b) (#\c) nil)
<pre>$ txr power-set-generic.txr
((nil) nil)
("" "a" "b" "c" "ab" "ac" "bc" "abc")
((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) nil)
("" "b")
("")
(#() #(1) #(2) #(3) #(1 2) #(1 3) #(2 3) #(1 2 3))</pre>
 
=={{header|UNIX Shell}}==
From [http://www.catonmat.net/blog/set-operations-in-unix-shell/ here]
<syntaxhighlight lang="bash">p() { [ $# -eq 0 ] && echo || (shift; p "$@") | while read r ; do echo -e "$1 $r\n$r"; done }</syntaxhighlight>
Usage
<syntaxhighlight lang="bash">|p `cat` | sort | uniq
A
C
E
^D</syntaxhighlight>
 
=={{header|UnixPipes}}==
<syntaxhighlight lang="ksh">
{{incomplete|UnixPipes|It shows no proof of the cases with empty sets.}}<lang ksh>| cat A
| cat A
a
b
Line 2,249 ⟶ 4,483:
b
b c
c
c</lang>
</syntaxhighlight>
 
=={{header|UNIX ShellUrsala}}==
{{incomplete|UNIX Shell|It shows no proof of the cases with empty sets.}}
From [http://www.catonmat.net/blog/set-operations-in-unix-shell/ here]
<lang bash>p() { [ $# -eq 0 ] && echo || (shift; p "$@") | while read r ; do echo -e "$1 $r\n$r"; done }</lang>
Usage
<lang bash>|p `cat` | sort | uniq
A
C
E
^D</lang>
 
Sets are a built in type constructor in Ursala, represented as
=={{header|Ursala}}==
lexically sorted lists with duplicates removed.
{{incomplete|Ursala|It shows no proof of the cases with empty sets.}}
Sets are a built in type constructor in Ursala, represented as lexically sorted lists with duplicates removed. The powerset function is a standard library function, but could be defined as shown below.
but could be defined as shown below.
<lang Ursala>powerset = ~&NiC+ ~&i&& ~&at^?\~&aNC ~&ahPfatPRXlNrCDrT</lang>
<syntaxhighlight lang="ursala">powerset = ~&NiC+ ~&i&& ~&at^?\~&aNC ~&ahPfatPRXlNrCDrT</syntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %sSS
 
test = powerset {'a','b','c','d'}</langsyntaxhighlight>
{{out}}
<pre>{
{
{},
{'a'},
Line 2,287 ⟶ 4,514:
{'c'},
{'c','d'},
{'d'}}</pre>
 
=={{header|V}}==
{{incomplete|V|It shows no proof of the cases with empty sets.}}
V has a built in called powerlist
<langsyntaxhighlight lang="v">[A C E] powerlist
=[[A C E] [A C] [A E] [A] [C E] [C] [E] []]</langsyntaxhighlight>
 
Its implementation in std.v is (like joy)
its implementation in std.v is (like joy)
<lang v>[powerlist
<syntaxhighlight lang="v">[powerlist
[null?]
[unitlist]
[uncons]
[dup swapd [cons] map popd swoncat]
linrec].</lang>
</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Option Base 1
Private Function power_set(ByRef st As Collection) As Collection
Dim subset As Collection, pwset As New Collection
For i = 0 To 2 ^ st.Count - 1
Set subset = New Collection
For j = 1 To st.Count
If i And 2 ^ (j - 1) Then subset.Add st(j)
Next j
pwset.Add subset
Next i
Set power_set = pwset
End Function
Private Function print_set(ByRef st As Collection) As String
'assume st is a collection of collections, holding integer variables
Dim s() As String, t() As String
ReDim s(st.Count)
'Debug.Print "{";
For i = 1 To st.Count
If st(i).Count > 0 Then
ReDim t(st(i).Count)
For j = 1 To st(i).Count
Select Case TypeName(st(i)(j))
Case "Integer": t(j) = CStr(st(i)(j))
Case "Collection": t(j) = "{}" 'assumes empty
End Select
Next j
s(i) = "{" & Join(t, ", ") & "}"
Else
s(i) = "{}"
End If
Next i
print_set = "{" & Join(s, ", ") & "}"
End Function
Public Sub rc()
Dim rcset As New Collection, result As Collection
For i = 1 To 4
rcset.Add i
Next i
Debug.Print print_set(power_set(rcset))
Set rcset = New Collection
Debug.Print print_set(power_set(rcset))
Dim emptyset As New Collection
rcset.Add emptyset
Debug.Print print_set(power_set(rcset))
Debug.Print
End Sub</syntaxhighlight>{{out}}
<pre>{{}, {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}}
{{}}
{{}, {{}}}</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">Function Dec2Bin(n)
q = n
Dec2Bin = ""
Do Until q = 0
Dec2Bin = CStr(q Mod 2) & Dec2Bin
q = Int(q / 2)
Loop
Dec2Bin = Right("00000" & Dec2Bin,6)
End Function
 
Function PowerSet(s)
arrS = Split(s,",")
PowerSet = "{"
For i = 0 To 2^(UBound(arrS)+1)-1
If i = 0 Then
PowerSet = PowerSet & "{},"
Else
binS = Dec2Bin(i)
PowerSet = PowerSet & "{"
c = 0
For j = Len(binS) To 1 Step -1
If CInt(Mid(binS,j,1)) = 1 Then
PowerSet = PowerSet & arrS(c) & ","
End If
c = c + 1
Next
PowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & "},"
End If
Next
PowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & "}"
End Function
 
WScript.StdOut.Write PowerSet("1,2,3,4")</syntaxhighlight>
{{out}}
<pre>{{},{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}}</pre>
 
=={{header|Wren}}==
{{libheader|Wren-perm}}
Although we have a module for sets, they are based on maps whose keys must be value types. This means that sets of sets are technically impossible because sets themselves are not value types.
 
We therefore use lists to represent sets which works fine here.
<syntaxhighlight lang="wren">import "./perm" for Powerset
 
var sets = [ [1, 2, 3, 4], [], [[]] ]
for (set in sets) {
System.print("The power set of %(set) is:")
System.print(Powerset.list(set))
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
The power set of [1, 2, 3, 4] is:
[[], [1], [2], [3], [4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]
 
The power set of [] is:
[[]]
 
The power set of [[]] is:
[[], [[]]]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func PowSet(Set, Size);
int Set, Size;
int N, M, Mask, DoComma;
[ChOut(0, ^{);
for N:= 0 to 1<<Size -1 do
[if N>0 then ChOut(0, ^,);
ChOut(0, ^{);
Mask:= 1; DoComma:= false;
for M:= 0 to Size-1 do
[if Mask & N then
[if DoComma then ChOut(0, ^,);
IntOut(0, Set(M));
DoComma:= true;
];
Mask:= Mask << 1;
];
ChOut(0, ^});
];
Text(0, "}^m^j");
];
 
[PowSet([2, 3, 5, 7], 4);
PowSet([1], 1);
PowSet(0, 0);
]</syntaxhighlight>
 
{{out}}
<pre>
{{},{2},{3},{2,3},{5},{2,5},{3,5},{2,3,5},{7},{2,7},{3,7},{2,3,7},{5,7},{2,5,7},{3,5,7},{2,3,5,7}}
{{},{1}}
{{}}
</pre>
 
=={{header|zkl}}==
Using a combinations function, build the power set from combinations of 1,2,... items.
<langsyntaxhighlight lang="zkl">fcn pwerSet(list){
(0).pump(list.len(),List, Utils.Helpers.pickNFrom.fp1(list),
T(Void.Write,Void.Write) ) .append(list)
}</langsyntaxhighlight>
<syntaxhighlight lang="zkl">foreach n in (5){
ps:=pwerSet((1).pump(n,List)); ps.println(" Size = ",ps.len());
}</syntaxhighlight>
{{out}}
<pre>
L(L()) Size = 1
foreach n in (5){
ps:=pwerSetL(L(1).pump,L(n,List1)); ps.println(" Size = ",ps.len());2
L(L(),L(1),L(2),L(1,2)) Size = 4
}</pre>
L(L(),L(1),L(2),L(3),L(1,2),L(1,3),L(2,3),L(1,2,3)) Size = 18
L(L(),L(1),L(2),L(3),L(4),L(1,2),L(1,3),L(1,4),L(2,3),L(2,4),
L(L(),L(1)) Size = 2
L(L(),L(1),L(2),L(1,2)) Size = 4
L(L(),L(1),L(2),L(3),L(1,2),L(1,3),L(2,3),L(1,2,3)) Size = 8
L(L(),L(1),L(2),L(3),L(4),L(1,2),L(1,3),L(1,4),L(2,3),L(2,4),
L(3,4),L(1,2,3),L(1,2,4),L(1,3,4),L(2,3,4),L(1,2,3,4)) Size = 16
</pre>
{{omit from|GUISS}}
2,120

edits