Power set: Difference between revisions

24,457 bytes added ,  1 month ago
m
(Updated to Nim 1.4: changed initSet to initHashSet, to Set to toHashSet. Also changed some variable names and some other things.)
 
(33 intermediate revisions by 18 users not shown)
Line 35:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F list_powerset(lst)
V result = [[Int]()]
L(x) lst
Line 41:
R result
 
print(list_powerset([1, 2, 3]))</langsyntaxhighlight>
 
{{out}}
Line 52:
This works for ABAP Version 7.40 and above
 
<syntaxhighlight lang="abap">
<lang ABAP>
report z_powerset.
 
Line 233:
)->add_element( `4` )->add_element( `4` ).
write: |𝑷( { set3->set~stringify( ) } ) -> { set3->build_powerset( )->set~stringify( ) }|, /.
</syntaxhighlight>
</lang>
 
{{out}}
Line 249:
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">
<lang Ada>
with Ada.Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Command_Line;
Line 272:
end loop;
end powerset;
</syntaxhighlight>
</lang>
 
 
Line 302:
 
Requires: ALGOL 68g mk14.1+
<langsyntaxhighlight lang="algol68">MODE MEMBER = INT;
 
PROC power set = ([]MEMBER s)[][]MEMBER:(
Line 328:
printf(($"set["d"] = "$,member, repr set, set[member],$l$))
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 344:
{{works with|Dyalog APL}}
 
<langsyntaxhighlight lang="apl">ps←(↓∘⍉(2/⍨≢)⊤(⍳2*≢))(/¨)⊂</langsyntaxhighlight>
 
{{out}}
Line 374:
(functional composition examples)
{{Trans|Haskell}}
<langsyntaxhighlight AppleScriptlang="applescript">-- POWER SET -----------------------------------------------------------------
 
-- powerset :: [a] -> [[a]]
Line 449:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}},
{"Empty set", {{}}},
{"Set containing only empty set", {{}, {{}}}}}</langsyntaxhighlight>
 
=={{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">
(* ****** ****** *)
//
Line 540 ⟶ 548:
 
(* ****** ****** *)
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=147 discussion]
<langsyntaxhighlight lang="autohotkey">a = 1,a,-- ; elements separated by commas
StringSplit a, a, `, ; a0 = #elements, a1,a2,... = elements of the set
 
Line 554 ⟶ 562:
t .= "}`n{" ; new subsets in new lines
}
MsgBox % RegExReplace(SubStr(t,1,StrLen(t)-1),",}","}")</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">cat power_set.awk
#!/usr/local/bin/gawk -f
 
Line 567 ⟶ 575:
# 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>
</lang>
 
{{out}}
Line 591 ⟶ 599:
</pre>
 
=={{header|BBC 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).
<langsyntaxhighlight lang="bbcbasic"> DIM list$(3) : list$() = "1", "2", "3", "4"
PRINT FNpowerset(list$())
END
Line 609 ⟶ 618:
s$ += "},"
NEXT i%
= LEFT$(s$) + "}"</langsyntaxhighlight>
{{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|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}}==
<langsyntaxhighlight lang="bracmat">( ( powerset
= done todo first
. !arg:(?done.?todo)
Line 625 ⟶ 643:
)
& out$(powerset$(.1 2 3 4))
);</langsyntaxhighlight>
{{out}}
<pre> 1 2 3 4
Line 646 ⟶ 664:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
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>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
struct node {
Line 682 ⟶ 700:
powerset(argv + 1, argc - 1, 0);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 697 ⟶ 715:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
Line 719 ⟶ 737:
}
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 742 ⟶ 760:
An alternative implementation for an arbitrary number of elements:
 
<langsyntaxhighlight lang="csharp">
public IEnumerable<IEnumerable<T>> GetPowerSet<T>(IEnumerable<T> input) {
var seed = new List<IEnumerable<T>>() { Enumerable.Empty<T>() }
Line 750 ⟶ 768:
a.Concat(a.Select(x => x.Concat(new List<T>() { b }))));
}
</syntaxhighlight>
</lang>
 
 
Non-recursive version
 
<langsyntaxhighlight lang="csharp">
using System;
class Powerset
Line 779 ⟶ 797:
}
}
</syntaxhighlight>
</lang>
 
----------------
Line 785 ⟶ 803:
 
Recursive version
<langsyntaxhighlight lang="csharp">
using System;
class Powerset
Line 807 ⟶ 825:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 813 ⟶ 831:
=== Non-recursive version ===
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <set>
#include <vector>
Line 890 ⟶ 908:
std::cout << " }\n";
}
}</langsyntaxhighlight>
 
{{out}}
Line 916 ⟶ 934:
This simplified version has identical output to the previous code.
 
<langsyntaxhighlight lang="cpp">
#include <set>
#include <iostream>
Line 951 ⟶ 969:
}
}
</syntaxhighlight>
</lang>
 
=== Recursive version ===
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <set>
 
Line 980 ⟶ 998:
return powerset(s, s.size());
}
</syntaxhighlight>
</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))
#{#{}} coll))
 
(powerset #{1 2 3})</langsyntaxhighlight>
<langsyntaxhighlight Clojurelang="clojure">#{#{} #{1} #{2} #{1 2} #{3} #{1 3} #{2 3} #{1 2 3}}</langsyntaxhighlight>
 
'''Using bit-test''':
see: https://clojuredocs.org/clojure.core/bit-test#example-5d401face4b0ca44402ef78b
<langsyntaxhighlight Clojurelang="clojure">(defn powerset [coll]
(let [cnt (count coll)
bits (Math/pow 2 cnt)]
Line 1,010 ⟶ 1,028:
(nth coll j)))))
 
(powerset [1 2 3])</langsyntaxhighlight>
<langsyntaxhighlight Clojurelang="clojure">(() (1) (2) (1 2) (3) (1 3) (2 3) (1 2 3))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
print_power_set = (arr) ->
console.log "POWER SET of #{arr}"
Line 1,043 ⟶ 1,061:
print_power_set [4, 2, 1]
print_power_set ['dog', 'c', 'b', 'a']
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
> coffee power_set.coffee
POWER SET of
Line 1,075 ⟶ 1,093:
[ 'dog', 'c', 'b' ]
[ 'dog', 'c', 'b', 'a' ]
</syntaxhighlight>
</lang>
 
=={{header|ColdFusion}}==
Line 1,081 ⟶ 1,099:
Port from the [[#JavaScript|JavaScript]] version,
compatible with ColdFusion 8+ or Railo 3+
<langsyntaxhighlight lang="javascript">public array function powerset(required array data)
{
var ps = [""];
Line 1,098 ⟶ 1,116:
}
 
var res = powerset([1,2,3,4]);</langsyntaxhighlight>
 
{{out}}
Line 1,104 ⟶ 1,122:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun powerset (s)
(if s (mapcan (lambda (x) (list (cons (car s) x) x))
(powerset (cdr s)))
'(())))</langsyntaxhighlight>
 
{{out}}
Line 1,113 ⟶ 1,131:
((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)
 
<langsyntaxhighlight lang="lisp">(defun power-set (s)
(reduce #'(lambda (item ps)
(append (mapcar #'(lambda (e) (cons item e))
Line 1,120 ⟶ 1,138:
s
:from-end t
:initial-value '(())))</langsyntaxhighlight>
{{out}}
>(power-set '(1 2 3))
Line 1,127 ⟶ 1,145:
 
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}}
>(powerset '(1 2 3)
Line 1,144 ⟶ 1,162:
 
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}}
>(power-set '(1 2 3))
Line 1,156 ⟶ 1,174:
This implementation defines a range which *lazily* enumerates the power set.
 
<langsyntaxhighlight lang="d">import std.algorithm;
import std.range;
 
Line 1,182 ⟶ 1,200:
import std.stdio;
args[1..$].powerSet.each!writeln;
}</langsyntaxhighlight>
 
An alternative version, which implements the range construct from scratch:
 
<langsyntaxhighlight lang="d">import std.range;
 
struct PowerSet(R)
Line 1,227 ⟶ 1,245:
}
 
auto powerSet(R)(R r) { return PowerSet!R(r); }</langsyntaxhighlight>
{{out}}
<pre>$ rdmd powerset a b c
Line 1,253 ⟶ 1,271:
#It doesn't rely on integer bit fiddling, so it should work on arrays larger than size_t.
 
<syntaxhighlight lang="d">
<lang d>
// Haskell definition:
// foldr f z [] = z
Line 1,270 ⟶ 1,288:
return foldr( (T x, T[][] acc) => acc ~ acc.map!(accx => x ~ accx).array , [[]], set );
}
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
Line 1,276 ⟶ 1,294:
In Déjà Vu, sets are dictionaries with all values <code>true</code> and the default set to <code>false</code>.
 
<langsyntaxhighlight lang="dejavu">powerset s:
local :out [ set{ } ]
for value in keys s:
Line 1,285 ⟶ 1,303:
out
 
!. powerset set{ 1 2 3 4 }</langsyntaxhighlight>
 
{{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}}==
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
 
def powerset(s) {
Line 1,300 ⟶ 1,373:
})
}
}</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="scheme">
(define (set-cons a A)
(make-set (cons a A)))
Line 1,337 ⟶ 1,410:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
use Bitwise
def powerset1(list) do
Line 1,369 ⟶ 1,442:
IO.inspect RC.powerset3([1,2,3])
IO.inspect RC.powerset1([])
IO.inspect RC.powerset1(["one"])</langsyntaxhighlight>
 
{{out}}
Line 1,395 ⟶ 1,468:
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
</pre>
<langsyntaxhighlight 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)].</langsyntaxhighlight>
 
{{out}}
Line 1,405 ⟶ 1,478:
 
Alternate shorter and more efficient version:
<langsyntaxhighlight lang="erlang">powerset([]) -> [[]];
powerset([H|T]) -> PT = powerset(T),
[ [H|X] || X <- PT ] ++ PT.</langsyntaxhighlight>
 
or even more efficient version:
<langsyntaxhighlight 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#}}==
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 [[]]
</syntaxhighlight>
</lang>
 
alternatively with list comprehension
 
<langsyntaxhighlight lang="fsharp">
let rec pow =
function
| [] -> [[]]
| x::xs -> [for i in pow xs do yield! [i;x::i]]
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
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.
<langsyntaxhighlight 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>
Usage:
<langsyntaxhighlight lang="factor">( scratchpad ) HS{ 1 2 3 4 } powerset .
HS{
HS{ 1 2 3 4 }
Line 1,458 ⟶ 1,531:
HS{ 1 3 4 }
HS{ 2 3 4 }
}</langsyntaxhighlight>
 
=={{header|Forth}}==
{{works with|4tH|3.61.0}}.
{{trans|C}}
<langsyntaxhighlight 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 1,470 ⟶ 1,543:
: powerset 1 argn check-none check-size 1- lshift .powerset ;
 
powerset</langsyntaxhighlight>
{{out}}
<pre>
Line 1,495 ⟶ 1,568:
=={{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).
<langsyntaxhighlight 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
Line 1,520 ⟶ 1,593:
Dim As String set1(0) = {""}
Print ConjuntoPotencia(set1())
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 1,536 ⟶ 1,609:
=={{header|Frink}}==
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.
<langsyntaxhighlight lang="frink">
a = new set[1,2,3,4]
a.subsets[]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
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.
 
<langsyntaxhighlight lang="funl">def powerset( s ) = s.subsets().toSet()</langsyntaxhighlight>
 
The powerset function could be implemented in FunL directly as:
 
<langsyntaxhighlight lang="funl">def
powerset( {} ) = {{}}
powerset( s ) =
acc = powerset( s.tail() )
acc + map( x -> {s.head()} + x, acc )</langsyntaxhighlight>
 
or, alternatively as:
<langsyntaxhighlight lang="funl">import lists.foldr
 
def powerset( s ) = foldr( \x, acc -> acc + map( a -> {x} + a, acc), {{}}, s )
 
println( powerset({1, 2, 3, 4}) )</langsyntaxhighlight>
 
{{out}}
Line 1,569 ⟶ 1,642:
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Power_set this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
No program needed. Power set is intrinsically supported in Fōrmulæ.
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
'''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]]
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
Combinations([1, 2, 3]);
# [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]
Line 1,583 ⟶ 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}}==
Line 1,592 ⟶ 1,691:
 
While the "add" and "has" methods make a usable set type, the power set method implemented here computes a result directly without using the add method. 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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,732 ⟶ 1,831:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,750 ⟶ 1,849:
=={{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'''.
<langsyntaxhighlight lang="groovy">
def powerSetRec(head, tail) {
if (!tail) return [head]
Line 1,757 ⟶ 1,856:
 
def powerSet(set) { powerSetRec([], set as List) as Set}
</syntaxhighlight>
</lang>
 
Test program:
<langsyntaxhighlight lang="groovy">
def vocalists = [ 'C', 'S', 'N', 'Y' ] as Set
println vocalists
println powerSet(vocalists)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,773 ⟶ 1,872:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.Set
import Control.Monad
 
Line 1,780 ⟶ 1,879:
 
listPowerset :: [a] -> [[a]]
listPowerset = filterM (const [True, False])</langsyntaxhighlight>
<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</langsyntaxhighlight>
or
<langsyntaxhighlight Haskelllang="haskell">powerSet :: [a] -> [[a]]
powerSet = foldr (\x acc -> acc ++ map (x:) acc) [[]]</langsyntaxhighlight>
 
which could also be understood, in point-free terms, as:
<langsyntaxhighlight lang="haskell">powerSet :: [a] -> [[a]]
powerSet = foldr ((mappend <*>) . fmap . (:)) (pure [])</langsyntaxhighlight>
 
Examples:
Line 1,809 ⟶ 1,908:
 
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.
<langsyntaxhighlight Haskelllang="haskell">import qualified Data.Set as Set
type Set=Set.Set
unionAll :: (Ord a) => Set (Set a) -> Set a
Line 1,823 ⟶ 1,922:
 
powerSet :: (Ord a) => Set a -> Set (Set a)
powerSet = (Set.fold (slift Set.union) (Set.singleton Set.empty)) . Set.map makeSet</langsyntaxhighlight>
Usage:
<syntaxhighlight lang="haskell">
<lang Haskell>
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]]</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,837 ⟶ 1,936:
The following version returns a set containing the powerset:
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure power_set (s)
result := set ()
Line 1,852 ⟶ 1,951:
return result
end
</syntaxhighlight>
</lang>
 
To test the above procedure:
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure main ()
every s := !power_set (set(1,2,3,4)) do { # requires '!' to generate items in the result set
Line 1,864 ⟶ 1,963:
}
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,890 ⟶ 1,989:
An alternative version, which generates each item in the power set in turn:
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure power_set (s)
if *s = 0
Line 1,910 ⟶ 2,009:
}
end
</syntaxhighlight>
</lang>
 
=={{header|J}}==
 
There are a [http://www.jsoftware.com/jwiki/Essays/Power_Set number of ways] to generate a power set in J. Here's one:
<langsyntaxhighlight lang="j">ps =: #~ 2 #:@i.@^ #</langsyntaxhighlight>
For example:
<langsyntaxhighlight lang="j"> ps 'ACE'
E
Line 1,925 ⟶ 2,024:
AE
AC
ACE</langsyntaxhighlight>
 
In the typical use, this operation makes sense on collections of unique elements.
 
<langsyntaxhighlight Jlang="j"> ~.1 2 3 2 1
1 2 3
#ps 1 2 3 2 1
32
#ps ~.1 2 3 2 1
8</langsyntaxhighlight>
 
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.
Line 1,943 ⟶ 2,042:
[[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.
<langsyntaxhighlight lang="java5">public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
{
if(n<0)
Line 1,967 ⟶ 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.
<langsyntaxhighlight lang="java5">
public static <T> List<List<T>> powerset(Collection<T> list) {
List<List<T>> ps = new ArrayList<List<T>>();
Line 1,995 ⟶ 2,094:
return ps;
}
</syntaxhighlight>
</lang>
 
===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.
<langsyntaxhighlight 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 2,014 ⟶ 2,113:
}
return ans;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,023 ⟶ 2,122:
 
{{works with|SpiderMonkey}}
<langsyntaxhighlight lang="javascript">function powerset(ary) {
var ps = [[]];
for (var i=0; i < ary.length; i++) {
Line 2,036 ⟶ 2,135:
 
load('json2.js');
print(JSON.stringify(res));</langsyntaxhighlight>
 
{{out}}
Line 2,046 ⟶ 2,145:
{{trans|Haskell}}
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// translating: powerset = foldr (\x acc -> acc ++ map (x:) acc) [[]]
Line 2,066 ⟶ 2,165:
}
 
})();</langsyntaxhighlight>
 
{{Out}}
 
<syntaxhighlight lang="javascript">{
<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 ->":[[], [[]]]
}</langsyntaxhighlight>
 
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,096 ⟶ 2,195:
])
};
})()</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="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 ->":[[], [[]]]}</langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def powerset:
reduce .[] as $i ([[]];
reduce .[] as $r (.; . + [$r + [$i]]));</langsyntaxhighlight>
Example:
[range(0;10)]|powerset|length
Line 2,112 ⟶ 2,211:
 
Extra credit:
<syntaxhighlight lang="jq">
<lang jq>
# The power set of the empty set:
[] | powerset
Line 2,119 ⟶ 2,218:
# The power set of the set which contains only the empty set:
[ [] ] | powerset
# => [[],[[]]]</langsyntaxhighlight>
====Recursive version====
<langsyntaxhighlight lang="jq">def powerset:
if length == 0 then [[]]
else .[0] as $first
| (.[1:] | powerset)
| map([$first] + . ) + .
end;</langsyntaxhighlight>
Example:
[1,2,3]|powerset
Line 2,132 ⟶ 2,231:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
function powerset{T}(x::Vector{T})::Vector{Vector{T}} where T
result = Vector{T}[[]]
for elem in x, j in eachindex(result)
Line 2,140 ⟶ 2,239:
result
end
</syntaxhighlight>
</lang>
{{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">
<lang K>
ps:{x@&:'+2_vs!_2^#x}
</syntaxhighlight>
</lang>
Usage:
<syntaxhighlight lang="k">
<lang K>
ps "ABC"
(""
Line 2,162 ⟶ 2,288:
"AB"
"ABC")
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// purely functional & lazy version, leveraging recursion and Sequences (a.k.a. streams)
fun <T> Set<T>.subsets(): Sequence<Set<T>> =
when (size) {
Line 2,191 ⟶ 2,317:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,220 ⟶ 2,346:
[[]]
</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}}==
<langsyntaxhighlight lang="logo">to powerset :set
if empty? :set [output [[]]]
localmake "rest powerset butfirst :set
Line 2,229 ⟶ 2,389:
 
show powerset [1 2 3]
[[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []]</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">:- object(set).
 
:- public(powerset/2).
Line 2,256 ⟶ 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}}==
<langsyntaxhighlight lang="lua">
--returns the powerset of s, out of order.
function powerset(s, start)
Line 2,298 ⟶ 2,458:
return ret
end
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`for',
`ifelse($#, 0, ``$0'',
eval($2 <= $3), 1,
Line 2,322 ⟶ 2,482:
`{powerpart(0, substr(`$1', 1, eval(len(`$1') - 2)))}')dnl
dnl
powerset(`{a,b,c}')</langsyntaxhighlight>
 
{{out}}
Line 2,330 ⟶ 2,490:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
combinat:-powerset({1,2,3,4});
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,340 ⟶ 2,500:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
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:
<langsyntaxhighlight Mathematicalang="mathematica">Subsets[{a, b, c}]</langsyntaxhighlight>
gives:
<langsyntaxhighlight Mathematicalang="mathematica">{{}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c}}</langsyntaxhighlight>
Subsets[list, {n, Infinity}] gives all the subsets that have n elements or more.
 
Line 2,360 ⟶ 2,520:
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.
 
<langsyntaxhighlight MATLABlang="matlab">function pset = powerset(theSet)
 
pset = cell(size(theSet)); %Preallocate memory
Line 2,377 ⟶ 2,537:
end
end</langsyntaxhighlight>
 
Sample Usage:
Powerset of the set of the empty set.
<langsyntaxhighlight MATLABlang="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}}==
<langsyntaxhighlight 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|Nim}}==
<langsyntaxhighlight lang="nim">import sets, hashes
proc hash(x: HashSet[int]): Hash =
Line 2,416 ⟶ 2,576:
result.incl(newSet)
echo powerset([1,2,3,4].toHashSet())</langsyntaxhighlight>
 
{{out}}
<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}}
</pre>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
+ (NSArray *)powerSetForArray:(NSArray *)array {
Line 2,434 ⟶ 2,598:
}
return subsets;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 2,440 ⟶ 2,604:
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.
 
<langsyntaxhighlight lang="ocaml">module PowerSet(S: Set.S) =
struct
 
Line 2,456 ⟶ 2,620:
;;
 
end;; (* PowerSet *)</langsyntaxhighlight>
 
version for lists:
<langsyntaxhighlight lang="ocaml">let subsets xs = List.fold_right (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]</langsyntaxhighlight>
 
=={{header|OPL}}==
 
<syntaxhighlight lang="opl">
<lang OPL>
{string} s={"A","B","C","D"};
range r=1.. ftoi(pow(2,card(s)));
Line 2,472 ⟶ 2,636:
writeln(s2);
}
</syntaxhighlight>
</lang>
 
which gives
 
<langsyntaxhighlight 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>
</lang>
 
=={{header|Oz}}==
Oz has a library for finite set constraints. Creating a power set is a trivial application of that:
<langsyntaxhighlight lang="oz">declare
%% Given a set as a list, returns its powerset (again as a list)
fun {Powerset Set}
Line 2,500 ⟶ 2,664:
end
in
{Inspect {Powerset [1 2 3 4]}}</langsyntaxhighlight>
 
A more convential implementation without finite set constaints:
<langsyntaxhighlight lang="oz">fun {Powerset2 Set}
case Set of nil then [nil]
[] H|T thens
Line 2,510 ⟶ 2,674:
{Append Acc {Map Acc fun {$ A} H|A end}}
end
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight 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.
<langsyntaxhighlight lang="parigp">S=["a","b","c"]
forsubset(#S,s,print1(vecextract(S,s)" "))</langsyntaxhighlight>
{{out}}
<pre>[] ["a"] ["b"] ["c"] ["a", "b"] ["a", "c"] ["b", "c"] ["a", "b", "c"]</pre>
Line 2,529 ⟶ 2,693:
 
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.
<langsyntaxhighlight lang="perl">use Algorithm::Combinatorics "subsets";
my @S = ("a","b","c");
my @PS;
Line 2,536 ⟶ 2,700:
push @PS, "[@$p]"
}
say join(" ",@PS);</langsyntaxhighlight>
{{out}}
<pre>[a b c] [b c] [a c] [c] [a b] [b] [a] []</pre>
Line 2,543 ⟶ 2,707:
{{libheader|ntheory}}
The simplest solution is to use the one argument version of the combination iterator, which iterates over the power set.
<langsyntaxhighlight lang="perl">use ntheory "forcomb";
my @S = qw/a b c/;
forcomb { print "[@S[@_]] " } scalar(@S);
print "\n";</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="perl">use ntheory "forcomb";
my @S = qw/a b c/;
for $k (0..@S) {
Line 2,557 ⟶ 2,721:
forcomb { print "[@S[@_]] " } @S,$k;
}
print "\n";</langsyntaxhighlight>
{{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.
<langsyntaxhighlight 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);</langsyntaxhighlight>
{{out}}
<pre>[] [a] [b] [a b] [c] [a c] [b c] [a b c]</pre>
Line 2,573 ⟶ 2,737:
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 2,586 ⟶ 2,750:
my $powerset = powerset($set);
 
print $powerset->as_string, "\n";</langsyntaxhighlight>
 
{{out}}
Line 2,596 ⟶ 2,760:
using a hash as the underlying representation (like the task description suggests):
 
<langsyntaxhighlight 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...
}</langsyntaxhighlight>
 
''(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])''
Line 2,609 ⟶ 2,773:
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:
 
<langsyntaxhighlight lang="perl">use List::Util qw(reduce);
 
sub powerset {
Line 2,619 ⟶ 2,783:
my @subsets = powerset($set);
 
print $_->as_string, "\n" for @subsets;</langsyntaxhighlight>
 
{{out}}
Line 2,638 ⟶ 2,802:
 
Recursive solution:
<langsyntaxhighlight lang="perl">sub powerset {
@_ ? map { $_, [$_[0], @$_] } powerset(@_[1..$#_]) : [];
}</langsyntaxhighlight>
 
List folding solution:
 
<langsyntaxhighlight lang="perl">use List::Util qw(reduce);
 
sub powerset {
@{( reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_ )}
}</langsyntaxhighlight>
 
Usage & output:
<langsyntaxhighlight lang="perl">my @set = (1, 2, 3);
my @powerset = powerset(@set);
 
Line 2,658 ⟶ 2,822:
}
 
print set_to_string(@powerset), "\n";</langsyntaxhighlight>
{{out}}
<pre>
Line 2,671 ⟶ 2,835:
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.
 
<langsyntaxhighlight lang="perl">use strict;
use warnings;
sub powerset :prototype(&@) {
my $callback = shift;
my $bitmask = '';
Line 2,692 ⟶ 2,856:
powerset { ++$i } 1..9;
print "The powerset of a nine element set contains $i elements.\n";
</syntaxhighlight>
</lang>
{{out}}
<pre>powerset of empty set:
Line 2,719 ⟶ 2,883:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence powerset
<span style="color: #004080;">sequence</span> <span style="color: #000000;">powerset</span>
integer step = 1
<span style="color: #004080;">integer</span> <span style="color: #000000;">step</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
 
function pst(object key, object /*data*/, object /*user_data*/)
<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>
integer k = 1
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
while k<length(powerset) do
<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>
k += step
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">step</span>
for j=1 to step do
<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>
powerset[k] = append(powerset[k],key)
<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>
k += 1
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
step *= 2
<span style="color: #000000;">step</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
return 1
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function power_set(integer d)
<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>
powerset = repeat({},power(2,dict_size(d)))
<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>
step = 1
<span style="color: #000000;">step</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
traverse_dict(routine_id("pst"),0,d)
<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>
return powerset
<span style="color: #008080;">return</span> <span style="color: #000000;">powerset</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
integer d1234 = new_dict()
<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>
setd(1,0,d1234)
<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>
setd(2,0,d1234)
<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>
setd(3,0,d1234)
<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>
setd(4,0,d1234)
<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>
?power_set(d1234)
<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>
integer d0 = new_dict()
<!--</syntaxhighlight>-->
?power_set(d0)
setd({},0,d0)
?power_set(d0)</lang>
{{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}}
{{}}
{{},{{}}}
Line 2,760 ⟶ 2,957:
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
<?php
function get_subset($binary, $arr) {
Line 2,820 ⟶ 3,017:
print_power_sets(array('dog', 'c', 'b', 'a'));
?>
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
POWER SET of []
POWER SET of [singleton]
Line 2,844 ⟶ 3,041:
b c dog
a b c dog
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de powerset (Lst)
(ifn Lst
(cons)
Line 2,853 ⟶ 3,050:
(conc
(mapcar '((X) (cons (car Lst) X)) L)
L ) ) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
{{trans|REXX}}
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
/*--------------------------------------------------------------------
* 06.01.2014 Walter Pachl translated from REXX
Line 2,922 ⟶ 3,119:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre>{}
Line 2,942 ⟶ 3,139:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function power-set ($array) {
if($array) {
Line 2,977 ⟶ 3,174:
$setC | foreach{"{"+"$_"+"}"}
$OFS = " "
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,016 ⟶ 3,213:
The definitions here are elementary, logical (cut-free),
and efficient (within the class of comparably generic implementations).
<langsyntaxhighlight Prologlang="prolog">powerset(X,Y) :- bagof( S, subseq(S,X), Y).
 
subseq( [], []).
Line 3,022 ⟶ 3,219:
subseq( [X|Xs], [X|Ys] ) :- subseq(Xs, Ys).
subseq( [X|Xs], [_|Ys] ) :- append(_, [X|Zs], Ys), subseq(Xs, Zs).
</syntaxhighlight>
</lang>
{{out}}
<pre>?- powerset([1,2,3], X).
Line 3,037 ⟶ 3,234:
 
===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}}
<pre>?- power_set([1,2,3,4,5,6,7,8], X), length(X,N), writeln(N).
Line 3,050 ⟶ 3,247:
CHR is a programming language created by '''Professor Thom Frühwirth'''.<br>
Works with SWI-Prolog and module chr written by '''Tom Schrijvers''' and '''Jan Wielemaker'''.
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(chr)).
 
:- chr_constraint chr_power_set/2, chr_power_set/1, clean/0.
Line 3,068 ⟶ 3,265:
 
empty_element @ chr_power_set([], _) <=> chr_power_set([]).
</langsyntaxhighlight>
{{out}}
<pre> ?- chr_power_set([1,2,3,4], []), findall(L, find_chr_constraint(chr_power_set(L)), LL), clean.
Line 3,076 ⟶ 3,273:
=={{header|PureBasic}}==
This code is for console mode.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define argc=CountProgramParameters()
If argc>=(SizeOf(Integer)*8) Or argc<1
Line 3,100 ⟶ 3,297:
PrintN("}")
EndIf
EndIf</langsyntaxhighlight>
<!-- Output modified with a line break to avoid being too long -->
{{out}}
Line 3,108 ⟶ 3,305:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def list_powerset(lst):
# the power set of the empty set has one element, the empty set
result = [[]]
Line 3,127 ⟶ 3,324:
 
def powerset(s):
return frozenset(map(frozenset, list_powerset(list(s))))</langsyntaxhighlight>
 
<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.
Line 3,141 ⟶ 3,338:
==== 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
<langsyntaxhighlight lang="python">def powersetlist(s):
r = [[]]
for e in s:
Line 3,149 ⟶ 3,346:
 
s= [0,1,2,3]
print "\npowersetlist(%r) =\n %r" % (s, powersetlist(s))</langsyntaxhighlight>
 
{{out}}
Line 3,164 ⟶ 3,361:
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)
<langsyntaxhighlight 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 3,188 ⟶ 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.
 
<langsyntaxhighlight lang="python">
def p(l):
if not l: return [[]]
return p(l[1:]) + [[l[0]] + x for x in p(l[1:])]
</syntaxhighlight>
</lang>
 
===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:
 
<langsyntaxhighlight lang="python">>>> from pprint import pprint as pp
>>> from itertools import chain, combinations
>>>
Line 3,227 ⟶ 3,424:
(3, 4),
(4,)}
>>> </langsyntaxhighlight>
 
=={{header|Qi}}==
{{trans|Scheme}}
<syntaxhighlight lang="qi">
<lang qi>
(define powerset
[] -> [[]]
[A|As] -> (append (map (cons A) (powerset As))
(powerset As)))
</syntaxhighlight>
</lang>
 
=={{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}}==
===Non-recursive version===
The conceptual basis for this algorithm is the following:
<syntaxhighlight lang="text">for each element in the set:
for each subset constructed so far:
new subset = (subset + element)
</syntaxhighlight>
</lang>
 
This method is much faster than a recursive method, though the speed is still O(2^n).
 
<langsyntaxhighlight Rlang="r">powerset <- function(set){
ps <- list()
ps[[1]] <- numeric() #Start with the empty set.
Line 3,262 ⟶ 3,551:
 
powerset(1:4)
</syntaxhighlight>
</lang>
 
The list "temp" is a compromise between the speed costs of doing
Line 3,274 ⟶ 3,563:
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.
<syntaxhighlight lang R="r">library(sets)</langsyntaxhighlight>
An example with a vector.
<langsyntaxhighlight Rlang="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.
<langsyntaxhighlight Rlang="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}}==
<langsyntaxhighlight lang="racket">
;;; Direct translation of 'functional' ruby method
(define (powerset s)
Line 3,295 ⟶ 3,584:
(list->set (set-map outer-set
(λ(inner-set) (set-add inner-set element)))))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2014-02-25}}
<syntaxhighlight lang="raku" perl6line>sub powerset(Set $s) { $s.combinations.map(*.Set).Set }
say powerset set <a b c d>;</langsyntaxhighlight>
{{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" perl6line>.say for <a b c d>.combinations</langsyntaxhighlight>
{{out}}
<pre>&nbsp;
Line 3,325 ⟶ 3,614:
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">
import Set;
 
public set[set[&T]] PowerSet(set[&T] s) = power(s);
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="rascal">
rascal>PowerSet({1,2,3,4})
set[set[int]]: {
Line 3,351 ⟶ 3,640:
{}
}
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program displays a power set; items may be anything (but can't have blanks).*/
parse arg S Parse Arg text /*allow the user specify optional set. */
ifIf Stext='' Then then S= 'one two three four' /*Not specified? Then use the default.*/
text='one two three four'
@= '{}' /*start process with a null power set. */
n=words(text)
N= words(S); do chunk=1 for N /*traipse through the items in the set.*/
psi=0
@=@ combN(N, chunk) /*take N items, a CHUNK at a time. */
Do k=0 To n end /* loops from 0 to n elements of a set /*chunk*/
w= length cc=comb(2**Nn,k) /* returns /*the numbercombinations of items1 inthrough thek power set.*/
Do while do k=1 for wordspos(@'/',cc) >0 /* [↓]as long showas combinations,there is a 1combination per line.*/
Parse Var cc elist '/' cc /* get i from comb's result string */
say right(k, w) word(@, k) /*display a single combination to term.*/
psl='' end /*k initialize the list of words */
exit 0 psi=psi+1 /* index of this set /*stick a fork in it, we're all done. */
Do While elist<>'' /* loop through elements */
/*──────────────────────────────────────────────────────────────────────────────────────*/
combN: procedure expose S; parse argvar x,y;elist e elist /* base=get xan +element 1;(a digit) bbase= base - y*/
psl=psl','word(text,e) /* add corresponding test word to set */
!.= 0
End
do p=1 for y; !.p= p
psl=substr(psl,2) /* get rid of leading comma end /*p*/
Say right(psi,2) '{'psl'}' /* show this element of the power set */
$= /* [↓] build powerset*/
End
do j=1; L=
End
do d=1 for y; L= L','word(S, !.d)
Exit
end /*d*/
comb: Procedure
$= $ '{'strip(L, "L", ',')"}"; !.y= !.y + 1
/***********************************************************************
if !.y==base then if .combU(y - 1) then leave
* Returns the combinations of size digits out of things digits
end /*j*/
* e.g. comb(4,2) -> ' 1 2/1 3/1 4/2 3/2 4/3 4/'
return strip($) /*return with a partial power set chunk*/
1 2/ 1 3/ 1 4/ 2 3/ 2 4/ 3 4 /
/*──────────────────────────────────────────────────────────────────────────────────────*/
***********************************************************************/
.combU: procedure expose !. y bbase; parse arg d; if d==0 then return 1
Parse Arg things,size
p= !.d
n=2**things-1
do u=d to y; !.u= p + 1; if !.u==bbase+u then return .combU(u-1)
list=''
p= !.u /* ↑ */
Do u=1 To n
end /*u*/ /*recurse──►───┘ */
co=combinations(u)
return 0</lang>
If co>'' Then
list=list '/' combinations(u)
End
Return substr(space(list),2) '/' /* remove leading / */
 
combinations: Procedure Expose things size
Parse Arg u
nc=0
bu=x2b(d2x(u))
bu1=space(translate(bu,' ',0),0)
If length(bu1)=size Then Do
ub=reverse(bu)
res=''
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>
Line 3,407 ⟶ 3,717:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Power set
 
Line 3,428 ⟶ 3,738:
next
return left(s,len(s)-1) + "}"
</syntaxhighlight>
</lang>
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}}==
<langsyntaxhighlight 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.
Line 3,478 ⟶ 3,824:
p %w(one two three).func_power_set
 
p Set[1,2,3].powerset</langsyntaxhighlight>
{{out}}
<pre>
Line 3,485 ⟶ 3,831:
#<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.
 
<langsyntaxhighlight lang="rust">use std::collections::BTreeSet;
 
fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> {
Line 3,519 ⟶ 3,864:
println!("{:?}", set);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,529 ⟶ 3,874:
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
options mprint mlogic symbolgen source source2;
 
Line 3,583 ⟶ 3,928:
%end;
%Mend SubSets;
</syntaxhighlight>
</lang>
 
You can then call the macro as:
<syntaxhighlight lang="sas">
<lang SAS>
%SubSets(FieldCount = 5);
</syntaxhighlight>
</lang>
 
The output will be the dataset SUBSETS
Line 3,632 ⟶ 3,977:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.compat.Platform.currentTime
 
object Powerset extends App {
Line 3,640 ⟶ 3,985:
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)))
println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}</langsyntaxhighlight>
 
Another option that produces lazy sequence of the sets:
<langsyntaxhighlight lang="scala">def powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet)</langsyntaxhighlight>
 
A tail-recursive version:
<langsyntaxhighlight 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
Line 3,652 ⟶ 3,997:
}
powerset_rec(List(Set.empty[A]), s.toList)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{trans|Common Lisp}}
<langsyntaxhighlight lang="scheme">(define (power-set set)
(if (null? set)
'(())
Line 3,668 ⟶ 4,013:
 
(display (power-set (list "A" "C" "E")))
(newline)</langsyntaxhighlight>
{{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:<langsyntaxhighlight lang="lisp">(define (power-set lst)
(define (iter yield)
(let recur ((a '()) (b lst))
Line 3,695 ⟶ 4,040:
(display a)
(newline)
(loop (x)))))</langsyntaxhighlight>
{{out}}
<pre>(1 2)
Line 3,705 ⟶ 4,050:
()</pre>
 
Iterative:<langsyntaxhighlight lang="scheme">
(define (power_set_iter set)
(let loop ((res '(())) (s set))
Line 3,711 ⟶ 4,056:
res
(loop (append (map (lambda (i) (cons (car s) i)) res) res) (cdr s)))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,750 ⟶ 4,095:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func array bitset: powerSet (in bitset: baseSet) is func
Line 3,778 ⟶ 4,123:
writeln(aSet);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,801 ⟶ 4,146:
 
=={{header|SETL}}==
<langsyntaxhighlight lang="haskell">Pfour := pow({1, 2, 3, 4});
Pempty := pow({});
PPempty := pow(Pempty);
Line 3,807 ⟶ 4,152:
print(Pfour);
print(Pempty);
print(PPempty);</langsyntaxhighlight>
 
{{out}}
Line 3,815 ⟶ 4,160:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = %w(a b c)
for i in (0 .. arr.len) {
say arr.combinations(i)
}</langsyntaxhighlight>
 
{{out}}
Line 3,829 ⟶ 4,174:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">SIMSET
BEGIN
 
Line 3,952 ⟶ 4,297:
END;
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,971 ⟶ 4,316:
Code from [http://smalltalk.gnu.org/blog/bonzinip/fun-generators Bonzini's blog]
 
<langsyntaxhighlight lang="smalltalk">Collection extend [
power [
^(0 to: (1 bitShift: self size) - 1) readStream collect: [ :each || i |
Line 3,977 ⟶ 4,322:
self select: [ :elem | (each bitAt: (i := i + 1)) = 1 ] ]
]
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">#(1 2 4) power do: [ :each |
each asArray printNl ].
 
#( 'A' 'C' 'E' ) power do: [ :each |
each asArray printNl ].</langsyntaxhighlight>
 
=={{header|Standard ML}}==
 
version for lists:
<langsyntaxhighlight lang="sml">fun subsets xs = foldr (fn (x, rest) => rest @ map (fn ys => x::ys) rest) [[]] xs</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|Revision 4 - tested with Xcode 9.2 playground}}
 
<langsyntaxhighlight Swiftlang="swift">func powersetFrom<T>(_ elements: Set<T>) -> Set<Set<T>> {
guard elements.count > 0 else {
return [[]]
Line 4,007 ⟶ 4,352:
 
// Example:
powersetFrom([1, 2, 4])</langsyntaxhighlight>
{{out}}
<pre>{
Line 4,020 ⟶ 4,365:
}</pre>
 
<langsyntaxhighlight Swiftlang="swift">//Example:
powersetFrom(["a", "b", "d"])</langsyntaxhighlight>
{{out}}
<pre>{
Line 4,035 ⟶ 4,380:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc subsets {l} {
set res [list [list]]
foreach e $l {
Line 4,042 ⟶ 4,387:
return $res
}
puts [subsets {a b c d}]</langsyntaxhighlight>
{{out}}
<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 4,057 ⟶ 4,402:
}
return $res
}</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 4,063 ⟶ 4,408:
The power set function can be written concisely like this:
 
<langsyntaxhighlight lang="txr">(defun power-set (s)
(mappend* (op comb s) (range 0 (length s))))</langsyntaxhighlight>
 
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.
Line 4,070 ⟶ 4,415:
A complete program which takes command line arguments and prints the power set in comma-separated brace notation:
 
<langsyntaxhighlight lang="txr">@(do (defun power-set (s)
(mappend* (op comb s) (range 0 (length s)))))
@(bind pset @(power-set *args*))
Line 4,077 ⟶ 4,422:
{@(rep)@pset, @(last)@pset@(empty)@(end)}
@ (end)
@(end)</langsyntaxhighlight>
{{out}}
<pre>$ txr rosetta/power-set.txr 1 2 3
Line 4,092 ⟶ 4,437:
generalizes to strings and vectors.
 
<langsyntaxhighlight 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>
{{out}}
<pre>$ txr power-set-generic.txr
Line 4,107 ⟶ 4,452:
=={{header|UNIX Shell}}==
From [http://www.catonmat.net/blog/set-operations-in-unix-shell/ here]
<langsyntaxhighlight lang="bash">p() { [ $# -eq 0 ] && echo || (shift; p "$@") | while read r ; do echo -e "$1 $r\n$r"; done }</langsyntaxhighlight>
Usage
<langsyntaxhighlight lang="bash">|p `cat` | sort | uniq
A
C
E
^D</langsyntaxhighlight>
 
=={{header|UnixPipes}}==
<langsyntaxhighlight lang="ksh">
| cat A
a
Line 4,139 ⟶ 4,484:
b c
c
</syntaxhighlight>
</lang>
 
=={{header|Ursala}}==
Line 4,147 ⟶ 4,492:
The powerset function is a standard library function,
but could be defined as shown below.
<langsyntaxhighlight Ursalalang="ursala">powerset = ~&NiC+ ~&i&& ~&at^?\~&aNC ~&ahPfatPRXlNrCDrT</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %sSS
 
test = powerset {'a','b','c','d'}</langsyntaxhighlight>
{{out}}
<pre>{
Line 4,173 ⟶ 4,518:
=={{header|V}}==
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)
<langsyntaxhighlight lang="v">[powerlist
[null?]
[unitlist]
Line 4,183 ⟶ 4,528:
[dup swapd [cons] map popd swoncat]
linrec].
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Base 1
Private Function power_set(ByRef st As Collection) As Collection
Dim subset As Collection, pwset As New Collection
Line 4,231 ⟶ 4,576:
Debug.Print print_set(power_set(rcset))
Debug.Print
End Sub</langsyntaxhighlight>{{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}}
{{}}
Line 4,237 ⟶ 4,582:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function Dec2Bin(n)
q = n
Dec2Bin = ""
Line 4,269 ⟶ 4,614:
End Function
 
WScript.StdOut.Write PowerSet("1,2,3,4")</langsyntaxhighlight>
{{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
<lang ecmascript>var powerset // recursive
powerset = Fn.new { |set|
if (set.count == 0) return [[]]
var head = set[0]
var tail = set[1..-1]
return powerset.call(tail) + powerset.call(tail).map { |s| [head] + s }
}
 
var sets = [ [1, 2, 3, 4], [], [[]] ]
for (set in sets) {
System.print("The power set of %(set) is:")
System.print(powersetPowerset.calllist(set))
System.print()
}</langsyntaxhighlight>
 
{{out}}
<pre>
The power set of [1, 2, 3, 4] is:
[[], [41], [32], [3], [4], [1, 2], [21, 43], [21, 34], [2, 3, 4], [1], [12, 4], [13, 34], [1, 32, 43], [1, 2, 4], [1, 23, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
 
The power set of [] is:
Line 4,302 ⟶ 4,642:
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>
<langsyntaxhighlight lang="zkl">foreach n in (5){
ps:=pwerSet((1).pump(n,List)); ps.println(" Size = ",ps.len());
}</langsyntaxhighlight>
{{out}}
<pre>
2,120

edits