Power set: Difference between revisions

Content deleted Content added
Added PicoLisp
Added a solution for MATLAB
Line 776: Line 776:


Subsets[list, {m,n}] gives all the subsets that have between m and n elements.
Subsets[list, {m,n}] gives all the subsets that have between m and n elements.

=={{header|MATLAB}}==

Sets are not an explicit data type in MATLAB, but cell arrays can be used for the same purpose. In fact, cell arrays have the benefit of containing any kind of data structure. So, this powerset function will work on a set of any type of data structure, without the need to overload any operators.
<lang MATLAB>function pset = powerset(set)

pset = {zeros(size(set))}; %Preallocate memory

%Generate all numbers from 0 to 2^(num elements of the set)-1
for i = ( 0:(2^numel(set))-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(set))));
%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) = {set(indicies)};
end
end</lang>

Sample Usage:
Powerset of the set of the empty set.
<lang MATLAB>powerset({{}})

ans =

{} {1x1 cell} %This is the same as { {},{{}} }</lang>

Powerset of { {1,2},3 }.
<lang 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}}</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==