Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Power_set
note: Discrete math

View file

@ -0,0 +1,30 @@
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.
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>

View file

@ -0,0 +1,7 @@
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]))

View file

@ -0,0 +1,180 @@
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( ) }|, /.

View file

@ -0,0 +1,27 @@
MODE MEMBER = INT;
PROC power set = ([]MEMBER s)[][]MEMBER:(
[2**UPB s]FLEX[1:0]MEMBER r;
INT upb r := 0;
r[upb r +:= 1] := []MEMBER(());
FOR i TO UPB s DO
MEMBER e = s[i];
FOR j TO upb r DO
[UPB r[j] + 1]MEMBER x;
x[:UPB x-1] := r[j];
x[UPB x] := e; # append to the end of x #
r[upb r +:= 1] := x # append to end of r #
OD
OD;
r[upb r] := s;
r
);
# Example: #
test:(
[][]MEMBER set = power set((1, 2, 4));
FOR member TO UPB set DO
INT upb = UPB set[member];
FORMAT repr set = $"("f( upb=0 | $$ | $n(upb-1)(d", ")d$ )");"$;
printf(($"set["d"] = "$,member, repr set, set[member],$l$))
OD
)

View file

@ -0,0 +1 @@
ps((2/)(2*))(/¨)

View file

@ -0,0 +1,83 @@
(* ****** ****** *)
//
#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] *)
(* ****** ****** *)

View file

@ -0,0 +1,10 @@
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)) }

View file

@ -0,0 +1,22 @@
with Ada.Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Command_Line;
procedure powerset is
begin
for set in 0..2**Argument_Count-1 loop
Put ("{");
declare
k : natural := set;
first : boolean := true;
begin
for i in 1..Argument_Count loop
if k mod 2 = 1 then
Put ((if first then "" else ",") & Argument (i));
first := false;
end if;
k := k / 2; -- we go to the next bit of "set"
end loop;
end;
Put_Line("}");
end loop;
end powerset;

View file

@ -0,0 +1,76 @@
-- 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

View file

@ -0,0 +1,3 @@
{{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}},
{"Empty set", {{}}},
{"Set containing only empty set", {{}, {{}}}}}

View file

@ -0,0 +1 @@
print powerset [1 2 3 4]

View file

@ -0,0 +1,11 @@
a = 1,a,-- ; elements separated by commas
StringSplit a, a, `, ; a0 = #elements, a1,a2,... = elements of the set
t = {
Loop % (1<<a0) { ; generate all 0-1 sequences
x := A_Index-1
Loop % a0
t .= (x>>A_Index-1) & 1 ? a%A_Index% "," : ""
t .= "}`n{" ; new subsets in new lines
}
MsgBox % RegExReplace(SubStr(t,1,StrLen(t)-1),",}","}")

View file

@ -0,0 +1,17 @@
DIM list$(3) : list$() = "1", "2", "3", "4"
PRINT FNpowerset(list$())
END
DEF FNpowerset(list$())
IF DIM(list$(),1) > 31 ERROR 100, "Set too large to represent as integer"
LOCAL i%, j%, s$
s$ = "{"
FOR i% = 0 TO (2 << DIM(list$(),1)) - 1
s$ += "{"
FOR j% = 0 TO DIM(list$(),1)
IF i% AND (1 << j%) s$ += list$(j%) + ","
NEXT
IF RIGHT$(s$) = "," s$ = LEFT$(s$)
s$ += "},"
NEXT i%
= LEFT$(s$) + "}"

View file

@ -0,0 +1 @@
P (·2˜)/¨<

View file

@ -0,0 +1,10 @@
( ( powerset
= done todo first
. !arg:(?done.?todo)
& ( !todo:%?first ?todo
& (powerset$(!done !first.!todo),powerset$(!done.!todo))
| !done
)
)
& out$(powerset$(.1 2 3 4))
);

View file

@ -0,0 +1,2 @@
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}}

View file

@ -0,0 +1,78 @@
#include <iostream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
typedef std::set<int> set_type;
typedef std::set<set_type> powerset_type;
powerset_type powerset(set_type const& set)
{
typedef set_type::const_iterator set_iter;
typedef std::vector<set_iter> vec;
typedef vec::iterator vec_iter;
struct local
{
static int dereference(set_iter v) { return *v; }
};
powerset_type result;
vec elements;
do
{
set_type tmp;
std::transform(elements.begin(), elements.end(),
std::inserter(tmp, tmp.end()),
local::dereference);
result.insert(tmp);
if (!elements.empty() && ++elements.back() == set.end())
{
elements.pop_back();
}
else
{
set_iter iter;
if (elements.empty())
{
iter = set.begin();
}
else
{
iter = elements.back();
++iter;
}
for (; iter != set.end(); ++iter)
{
elements.push_back(iter);
}
}
} while (!elements.empty());
return result;
}
int main()
{
int values[4] = { 2, 3, 5, 7 };
set_type test_set(values, values+4);
powerset_type test_powerset = powerset(test_set);
for (powerset_type::iterator iter = test_powerset.begin();
iter != test_powerset.end();
++iter)
{
std::cout << "{ ";
char const* prefix = "";
for (set_type::iterator iter2 = iter->begin();
iter2 != iter->end();
++iter2)
{
std::cout << prefix << *iter2;
prefix = ", ";
}
std::cout << " }\n";
}
}

View file

@ -0,0 +1,34 @@
#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";
}
}

View file

@ -0,0 +1,25 @@
#include <iostream>
#include <set>
template<typename Set> std::set<Set> powerset(const Set& s, size_t n)
{
typedef typename Set::const_iterator SetCIt;
typedef typename std::set<Set>::const_iterator PowerSetCIt;
std::set<Set> res;
if(n > 0) {
std::set<Set> ps = powerset(s, n-1);
for(PowerSetCIt ss = ps.begin(); ss != ps.end(); ss++)
for(SetCIt el = s.begin(); el != s.end(); el++) {
Set subset(*ss);
subset.insert(*el);
res.insert(subset);
}
res.insert(ps.begin(), ps.end());
} else
res.insert(Set());
return res;
}
template<typename Set> std::set<Set> powerset(const Set& s)
{
return powerset(s, s.size());
}

View file

@ -0,0 +1,20 @@
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()));
}

View file

@ -0,0 +1,7 @@
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 }))));
}

View file

@ -0,0 +1,23 @@
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);
}
}

View file

@ -0,0 +1,22 @@
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);
}
}
}

View file

@ -0,0 +1,31 @@
#include <stdio.h>
struct node {
char *s;
struct node* prev;
};
void powerset(char **v, int n, struct node *up)
{
struct node me;
if (!n) {
putchar('[');
while (up) {
printf(" %s", up->s);
up = up->prev;
}
puts(" ]");
} else {
me.s = *v;
me.prev = up;
powerset(v + 1, n - 1, up);
powerset(v + 1, n - 1, &me);
}
}
int main(int argc, char **argv)
{
powerset(argv + 1, argc - 1, 0);
return 0;
}

View file

@ -0,0 +1,6 @@
(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))

View file

@ -0,0 +1,6 @@
(defn powerset [coll]
(reduce (fn [a x]
(into a (map #(conj % x)) a))
#{#{}} coll))
(powerset #{1 2 3})

View file

@ -0,0 +1 @@
#{#{} #{1} #{2} #{1 2} #{3} #{1 3} #{2 3} #{1 2 3}}

View file

@ -0,0 +1,10 @@
(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])

View file

@ -0,0 +1 @@
(() (1) (2) (1 2) (3) (1 3) (2 3) (1 2 3))

View file

@ -0,0 +1,28 @@
print_power_set = (arr) ->
console.log "POWER SET of #{arr}"
for subset in power_set(arr)
console.log subset
power_set = (arr) ->
result = []
binary = (false for elem in arr)
n = arr.length
while binary.length <= n
result.push bin_to_arr binary, arr
i = 0
while true
if binary[i]
binary[i] = false
i += 1
else
binary[i] = true
break
binary[i] = true
result
bin_to_arr = (binary, arr) ->
(arr[i] for i of binary when binary[arr.length - i - 1])
print_power_set []
print_power_set [4, 2, 1]
print_power_set ['dog', 'c', 'b', 'a']

View file

@ -0,0 +1,29 @@
> coffee power_set.coffee
POWER SET of
[]
POWER SET of 4,2,1
[]
[ 1 ]
[ 2 ]
[ 2, 1 ]
[ 4 ]
[ 4, 1 ]
[ 4, 2 ]
[ 4, 2, 1 ]
POWER SET of dog,c,b,a
[]
[ 'a' ]
[ 'b' ]
[ 'b', 'a' ]
[ 'c' ]
[ 'c', 'a' ]
[ 'c', 'b' ]
[ 'c', 'b', 'a' ]
[ 'dog' ]
[ 'dog', 'a' ]
[ 'dog', 'b' ]
[ 'dog', 'b', 'a' ]
[ 'dog', 'c' ]
[ 'dog', 'c', 'a' ]
[ 'dog', 'c', 'b' ]
[ 'dog', 'c', 'b', 'a' ]

View file

@ -0,0 +1,18 @@
public array function powerset(required array data)
{
var ps = [""];
var d = arguments.data;
var lenData = arrayLen(d);
var lenPS = 0;
for (var i=1; i LTE lenData; i++)
{
lenPS = arrayLen(ps);
for (var j = 1; j LTE lenPS; j++)
{
arrayAppend(ps, listAppend(ps[j], d[i]));
}
}
return ps;
}
var res = powerset([1,2,3,4]);

View file

@ -0,0 +1,4 @@
(defun powerset (s)
(if s (mapcan (lambda (x) (list (cons (car s) x) x))
(powerset (cdr s)))
'(())))

View file

@ -0,0 +1,8 @@
(defun power-set (s)
(reduce #'(lambda (item ps)
(append (mapcar #'(lambda (e) (cons item e))
ps)
ps))
s
:from-end t
:initial-value '(())))

View file

@ -0,0 +1,6 @@
(defun powerset (l)
(if (null l)
(list nil)
(let ((prev (powerset (cdr l))))
(append (mapcar #'(lambda (elt) (cons (car l) elt)) prev)
prev))))

View file

@ -0,0 +1,3 @@
(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)))

View file

@ -0,0 +1,5 @@
(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)))))

View file

@ -0,0 +1,27 @@
import std.algorithm;
import std.range;
auto powerSet(R)(R r)
{
return
(1L<<r.length)
.iota
.map!(i =>
r.enumerate
.filter!(t => (1<<t[0]) & i)
.map!(t => t[1])
);
}
unittest
{
int[] emptyArr;
assert(emptyArr.powerSet.equal!equal([emptyArr]));
assert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]]));
}
void main(string[] args)
{
import std.stdio;
args[1..$].powerSet.each!writeln;
}

View file

@ -0,0 +1,42 @@
import std.range;
struct PowerSet(R)
if (isRandomAccessRange!R)
{
R r;
size_t position;
struct PowerSetItem
{
R r;
size_t position;
private void advance()
{
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); }

View file

@ -0,0 +1,16 @@
// 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 );
}

View file

@ -0,0 +1,30 @@
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.

View file

@ -0,0 +1,15 @@
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)

View file

@ -0,0 +1,9 @@
pragma.enable("accumulator")
def powerset(s) {
return accum [].asSet() for k in 0..!2**s.size() {
_.with(accum [].asSet() for i ? ((2**i & k) > 0) => elem in s {
_.with(elem)
})
}
}

View file

@ -0,0 +1,29 @@
(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

View file

@ -0,0 +1,29 @@
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"])

View file

@ -0,0 +1,5 @@
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)].

View file

@ -0,0 +1,3 @@
powerset([]) -> [[]];
powerset([H|T]) -> PT = powerset(T),
[ [H|X] || X <- PT ] ++ PT.

View file

@ -0,0 +1,6 @@
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]).

View file

@ -0,0 +1 @@
let subsets xs = List.foldBack (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]

View file

@ -0,0 +1,4 @@
let rec pow =
function
| [] -> [[]]
| x::xs -> [for i in pow xs do yield! [i;x::i]]

View file

@ -0,0 +1,5 @@
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> ;

View file

@ -0,0 +1,19 @@
( scratchpad ) HS{ 1 2 3 4 } powerset .
HS{
HS{ 1 2 3 4 }
HS{ 1 2 }
HS{ 1 3 }
HS{ 2 3 }
HS{ 1 2 3 }
HS{ 1 4 }
HS{ 2 4 }
HS{ }
HS{ 1 }
HS{ 2 }
HS{ 3 }
HS{ 4 }
HS{ 1 2 4 }
HS{ 3 4 }
HS{ 1 3 4 }
HS{ 2 3 4 }
}

View file

@ -0,0 +1,8 @@
: ?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 ;
: check-none dup 2 < abort" Usage: powerset [val] .. [val]" ;
: check-size dup /cell 8 [*] >= abort" Set too large" ;
: powerset 1 argn check-none check-size 1- lshift .powerset ;
powerset

View file

@ -0,0 +1,26 @@
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

View file

@ -0,0 +1,2 @@
a = new set[1,2,3,4]
a.subsets[]

View file

@ -0,0 +1 @@
def powerset( s ) = s.subsets().toSet()

View file

@ -0,0 +1,5 @@
def
powerset( {} ) = {{}}
powerset( s ) =
acc = powerset( s.tail() )
acc + map( x -> {s.head()} + x, acc )

View file

@ -0,0 +1,5 @@
import lists.foldr
def powerset( s ) = foldr( \x, acc -> acc + map( a -> {x} + a, acc), {{}}, s )
println( powerset({1, 2, 3, 4}) )

View file

@ -0,0 +1,8 @@
# Built-in
Combinations([1, 2, 3]);
# [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]
# Note that it handles duplicates
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 ] ]

View file

@ -0,0 +1,141 @@
package main
import (
"fmt"
"strconv"
"strings"
)
// types needed to implement general purpose sets are element and set
// element is an interface, allowing different kinds of elements to be
// implemented and stored in sets.
type elem interface {
// an element must be distinguishable from other elements to satisfy
// the mathematical definition of a set. a.eq(b) must give the same
// result as b.eq(a).
Eq(elem) 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().
fmt.Stringer
}
// integer type satisfying element interface
type Int int
func (i Int) Eq(e elem) bool {
j, ok := e.(Int)
return ok && i == j
}
func (i Int) String() string {
return strconv.Itoa(int(i))
}
// a set is a slice of elem's. methods are added to implement
// the element interface, to allow nesting.
type set []elem
// uniqueness of elements can be ensured by using add method
func (s *set) add(e elem) {
if !s.has(e) {
*s = append(*s, e)
}
}
func (s *set) has(e elem) bool {
for _, ex := range *s {
if e.Eq(ex) {
return true
}
}
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
}
// elem.Eq
func (s set) Eq(e elem) bool {
t, ok := e.(set)
if !ok {
return false
}
if len(s) != len(t) {
return false
}
for _, se := range s {
if !t.has(se) {
return false
}
}
return true
}
// elem.String
func (s set) String() string {
if len(s) == 0 {
return "∅"
}
var buf strings.Builder
buf.WriteRune('{')
for i, e := range s {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(e.String())
}
buf.WriteRune('}')
return buf.String()
}
// method required for task
func (s set) powerSet() set {
r := set{set{}}
for _, es := range s {
var u set
for _, er := range r {
er := er.(set)
u = append(u, append(er[:len(er):len(er)], es))
}
r = append(r, u...)
}
return r
}
func main() {
var s set
for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} {
s.add(i)
}
fmt.Println(" s:", s, "length:", len(s))
ps := s.powerSet()
fmt.Println(" 𝑷(s):", ps, "length:", len(ps))
fmt.Println("\n(extra credit)")
var empty set
fmt.Println(" empty:", empty, "len:", len(empty))
ps = empty.powerSet()
fmt.Println(" 𝑷(∅):", ps, "len:", len(ps))
ps = ps.powerSet()
fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps))
fmt.Println("\n(regression test for earlier bug)")
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")
}
}
}

View file

@ -0,0 +1,6 @@
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}

View file

@ -0,0 +1,3 @@
def vocalists = [ 'C', 'S', 'N', 'Y' ] as Set
println vocalists
println powerSet(vocalists)

View file

@ -0,0 +1,8 @@
import Data.Set
import Control.Monad
powerset :: Ord a => Set a -> Set (Set a)
powerset = fromList . fmap fromList . listPowerset . toList
listPowerset :: [a] -> [[a]]
listPowerset = filterM (const [True, False])

View file

@ -0,0 +1,2 @@
powerset [] = [[]]
powerset (head:tail) = acc ++ map (head:) acc where acc = powerset tail

View file

@ -0,0 +1,2 @@
powerSet :: [a] -> [[a]]
powerSet = foldr (\x acc -> acc ++ map (x:) acc) [[]]

View file

@ -0,0 +1,2 @@
powerSet :: [a] -> [[a]]
powerSet = foldr ((mappend <*>) . fmap . (:)) (pure [])

View file

@ -0,0 +1,15 @@
import qualified Data.Set as Set
type Set=Set.Set
unionAll :: (Ord a) => Set (Set a) -> Set a
unionAll = Set.fold Set.union Set.empty
--slift is the analogue of liftA2 for sets.
slift :: (Ord a, Ord b, Ord c) => (a->b->c) -> Set a -> Set b -> Set c
slift f s0 s1 = unionAll (Set.map (\e->Set.map (f e) s1) s0)
--a -> {{},{a}}
makeSet :: (Ord a) => a -> Set (Set a)
makeSet = (Set.insert Set.empty) . Set.singleton.Set.singleton
powerSet :: (Ord a) => Set a -> Set (Set a)
powerSet = (Set.fold (slift Set.union) (Set.singleton Set.empty)) . Set.map makeSet

View file

@ -0,0 +1,2 @@
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]]

View file

@ -0,0 +1,14 @@
procedure power_set (s)
result := set ()
if *s = 0
then insert (result, set ()) # empty set
else {
head := set(?s) # take a random element
# and find powerset of remaining part of set
tail_pset := power_set (x -- head)
result ++:= tail_pset # add powerset of remainder to results
every ps := !tail_pset do # and add head to each powerset from the remainder
insert (result, ps ++ head)
}
return result
end

View file

@ -0,0 +1,7 @@
procedure main ()
every s := !power_set (set(1,2,3,4)) do { # requires '!' to generate items in the result set
writes ("[ ")
every writes (!s || " ")
write ("]")
}
end

View file

@ -0,0 +1,19 @@
procedure power_set (s)
if *s = 0
then suspend set ()
else {
head := set(?s)
every ps := power_set (s -- head) do {
suspend ps
suspend ps ++ head
}
}
end
procedure main ()
every s := power_set (set(1,2,3,4)) do { # power_set's values are generated by 'every'
writes ("[ ")
every writes (!s || " ")
write ("]")
}
end

View file

@ -0,0 +1 @@
ps =: #~ 2 #:@i.@^ #

View file

@ -0,0 +1,9 @@
ps 'ACE'
E
C
CE
A
AE
AC
ACE

View file

@ -0,0 +1,6 @@
~.1 2 3 2 1
1 2 3
#ps 1 2 3 2 1
32
#ps ~.1 2 3 2 1
8

View file

@ -0,0 +1,25 @@
public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
{
if(n<0)
{
return null;
}
if(n==0)
{
if(ps==null)
ps=new ArrayList<String>();
ps.add(" ");
return ps;
}
ps=getpowerset(a, n-1, ps);
ArrayList<String> tmp=new ArrayList<String>();
for(String s:ps)
{
if(s.equals(" "))
tmp.add(""+a[n-1]);
else
tmp.add(s+a[n-1]);
}
ps.addAll(tmp);
return ps;
}

View file

@ -0,0 +1,23 @@
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
// for every item in the original list
for (T item : list) {
List<List<T>> newPs = new ArrayList<List<T>>();
for (List<T> subset : ps) {
// copy all of the current powerset's subsets
newPs.add(subset);
// plus the subsets appended with the current item
List<T> newSubset = new ArrayList<T>(subset);
newSubset.add(item);
newPs.add(newSubset);
}
// powerset is now powerset of list.subList(0, list.indexOf(item)+1)
ps = newPs;
}
return ps;
}

View file

@ -0,0 +1,16 @@
public static <T extends Comparable<? super T>> LinkedList<LinkedList<T>> BinPowSet(
LinkedList<T> A){
LinkedList<LinkedList<T>> ans= new LinkedList<LinkedList<T>>();
int ansSize = (int)Math.pow(2, A.size());
for(int i= 0;i< ansSize;++i){
String bin= Integer.toBinaryString(i); //convert to binary
while(bin.length() < A.size()) bin = "0" + bin; //pad with 0's
LinkedList<T> thisComb = new LinkedList<T>(); //place to put one combination
for(int j= 0;j< A.size();++j){
if(bin.charAt(j) == '1')thisComb.add(A.get(j));
}
Collections.sort(thisComb); //sort it for easy checking
ans.add(thisComb); //put this set in the answer list
}
return ans;
}

View file

@ -0,0 +1,14 @@
function powerset(ary) {
var ps = [[]];
for (var i=0; i < ary.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(ary[i]));
}
}
return ps;
}
var res = powerset([1,2,3,4]);
load('json2.js');
print(JSON.stringify(res));

View file

@ -0,0 +1,21 @@
(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([[]])
}
})();

View file

@ -0,0 +1,5 @@
{
"[1,2,3] ->":[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]],
"empty set ->":[[]],
"set which contains only the empty set ->":[[], [[]]]
}

View file

@ -0,0 +1,19 @@
(() => {
'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([
[]
])
};
})()

View file

@ -0,0 +1,3 @@
{"[1,2,3] ->":[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]],
"empty set ->":[[]],
"set which contains only the empty set ->":[[], [[]]]}

View file

@ -0,0 +1,3 @@
def powerset:
reduce .[] as $i ([[]];
reduce .[] as $r (.; . + [$r + [$i]]));

View file

@ -0,0 +1,7 @@
# The power set of the empty set:
[] | powerset
# => [[]]
# The power set of the set which contains only the empty set:
[ [] ] | powerset
# => [[],[[]]]

View file

@ -0,0 +1,6 @@
def powerset:
if length == 0 then [[]]
else .[0] as $first
| (.[1:] | powerset)
| map([$first] + . ) + .
end;

View file

@ -0,0 +1,7 @@
function powerset(x::Vector{T})::Vector{Vector{T}} where T
result = Vector{T}[[]]
for elem in x, j in eachindex(result)
push!(result, [result[j] ; elem])
end
result
end

View file

@ -0,0 +1,18 @@
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

View file

@ -0,0 +1 @@
ps:{x@&:'+2_vs!_2^#x}

View file

@ -0,0 +1,9 @@
ps "ABC"
(""
,"C"
,"B"
"BC"
,"A"
"AC"
"AB"
"ABC")

View file

@ -0,0 +1,26 @@
// 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)
}
}
}
}

View file

@ -0,0 +1,29 @@
{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]]]

View file

@ -0,0 +1,8 @@
to powerset :set
if empty? :set [output [[]]]
localmake "rest powerset butfirst :set
output sentence map [sentence first :set ?] :rest :rest
end
show powerset [1 2 3]
[[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []]

View file

@ -0,0 +1,25 @@
:- object(set).
:- public(powerset/2).
powerset(Set, PowerSet) :-
reverse(Set, RSet),
powerset_1(RSet, [[]], PowerSet).
powerset_1([], PowerSet, PowerSet).
powerset_1([X| Xs], Yss0, Yss) :-
powerset_2(Yss0, X, Yss1),
powerset_1(Xs, Yss1, Yss).
powerset_2([], _, []).
powerset_2([Zs| Zss], X, [Zs, [X| Zs]| Yss]) :-
powerset_2(Zss, X, Yss).
reverse(List, Reversed) :-
reverse(List, [], Reversed).
reverse([], Reversed, Reversed).
reverse([Head| Tail], List, Reversed) :-
reverse(Tail, [Head| List], Reversed).
:- end_object.

View file

@ -0,0 +1,4 @@
| ?- 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

View file

@ -0,0 +1,33 @@
--returns the powerset of s, out of order.
function powerset(s, start)
start = start or 1
if(start > #s) then return {{}} end
local ret = powerset(s, start + 1)
for i = 1, #ret do
ret[#ret + 1] = {s[start], unpack(ret[i])}
end
return ret
end
--non-recurse implementation
function powerset(s)
local t = {{}}
for i = 1, #s do
for j = 1, #t do
t[#t+1] = {s[i],unpack(t[j])}
end
end
return t
end
--alternative, copied from the Python implementation
function powerset2(s)
local ret = {{}}
for i = 1, #s do
local k = #ret
for j = 1, k do
ret[k + j] = {s[i], unpack(ret[j])}
end
end
return ret
end

View file

@ -0,0 +1,22 @@
define(`for',
`ifelse($#, 0, ``$0'',
eval($2 <= $3), 1,
`pushdef(`$1', `$2')$4`'popdef(
`$1')$0(`$1', incr($2), $3, `$4')')')dnl
define(`nth',
`ifelse($1, 1, $2,
`nth(decr($1), shift(shift($@)))')')dnl
define(`range',
`for(`x', eval($1 + 2), eval($2 + 2),
`nth(x, $@)`'ifelse(x, eval($2+2), `', `,')')')dnl
define(`powerpart',
`{range(2, incr($1), $@)}`'ifelse(incr($1), $#, `',
`for(`x', eval($1+2), $#,
`,powerpart(incr($1), ifelse(
eval(2 <= ($1 + 1)), 1,
`range(2,incr($1), $@), ')`'nth(x, $@)`'ifelse(
eval((x + 1) <= $#),1,`,range(incr(x), $#, $@)'))')')')dnl
define(`powerset',
`{powerpart(0, substr(`$1', 1, eval(len(`$1') - 2)))}')dnl
dnl
powerset(`{a,b,c}')

View file

@ -0,0 +1,18 @@
function pset = powerset(theSet)
pset = cell(size(theSet)); %Preallocate memory
%Generate all numbers from 0 to 2^(num elements of the set)-1
for i = ( 0:(2^numel(theSet))-1 )
%Convert i into binary, convert each digit in binary to a boolean
%and store that array of booleans
indicies = logical(bitget( i,(1:numel(theSet)) ));
%Use the array of booleans to extract the members of the original
%set, and store the set containing these members in the powerset
pset(i+1) = {theSet(indicies)};
end
end

View file

@ -0,0 +1,5 @@
powerset({{}})
ans =
{} {1x1 cell} %This is the same as { {},{{}} }

View file

@ -0,0 +1,5 @@
powerset({{1,2},3})
ans =
{1x0 cell} {1x1 cell} {1x1 cell} {1x2 cell} %This is the same as { {},{{1,2}},{3},{{1,2},3} }

Some files were not shown because too many files have changed in this diff Show more