Power set: Difference between revisions

2,038 bytes removed ,  6 years ago
Line 34:
=={{header|Ada}}==
 
AnotherA 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.
We start with specifying a generic package Power_Set, which holds a set of positive integers. Actually, it holds a multiset, i.e., integers are allowed to occur more than once.
 
<lang Ada>package Power_Set is
type Set is array (Positive range <>) of Positive;
Empty_Set: Set(1 .. 0);
generic
with procedure Visit(S: Set);
procedure All_Subsets(S: Set); -- calles Visit once for each subset of S
end Power_Set;</lang>
 
The implementation of Power_Set is as follows:
 
<lang Ada>package body Power_Set is
procedure All_Subsets(S: Set) is
procedure Visit_Sets(Unmarked: Set; Marked: Set) is
Tail: Set := Unmarked(Unmarked'First+1 .. Unmarked'Last);
begin
if Unmarked = Empty_Set then
Visit(Marked);
else
Visit_Sets(Tail, Marked & Unmarked(Unmarked'First));
Visit_Sets(Tail, Marked);
end if;
end Visit_Sets;
begin
Visit_Sets(S, Empty_Set);
end All_Subsets;
end Power_Set;</lang>
 
The main program prints the power set of words read from the command line.
 
<lang ada>with Ada.Text_IO, Ada.Command_Line, Power_Set;
 
procedure Print_Power_Set is
procedure Print_Set(Items: Power_Set.Set) is
First: Boolean := True;
begin
Ada.Text_IO.Put("{ ");
for Item of Items loop
if First then
First := False; -- no comma needed
else
Ada.Text_IO.Put(", "); -- comma, to separate the items
end if;
Ada.Text_IO.Put(Ada.Command_Line.Argument(Item));
end loop;
Ada.Text_IO.Put_Line(" }");
end Print_Set;
procedure Print_All_Subsets is new Power_Set.All_Subsets(Print_Set);
Set: Power_Set.Set(1 .. Ada.Command_Line.Argument_Count);
begin
for I in Set'Range loop -- initialize set
Set(I) := I;
end loop;
Print_All_Subsets(Set); -- do the work
end;</lang>
 
{{out}}
 
<pre>>./power_set cat dog mouse
{ cat, dog, mouse }
{ cat, dog }
{ cat, mouse }
{ cat }
{ dog, mouse }
{ dog }
{ mouse }
{ }
>./power_set 1 2
{ 1, 2 }
{ 1 }
{ 2 }
{ }</pre>
 
----
 
Another 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.
 
<lang Ada>
Anonymous user