Power set: Difference between revisions

Line 117:
{ 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>
with ada.text_io, Ada.Command_Line;
 
procedure powerset is
procedure print_subset (set : natural) is
-- each i'th binary digit of "set" indicates if the i'th integer belongs to "set" or not.
k : natural := set;
first : boolean := true;
begin
Ada.Text_IO.put ("{");
for i in 1..Ada.Command_Line.Argument_Count loop
if k mod 2 = 1 then
if first then
first := false;
else
Ada.Text_IO.put (",");
end if;
Ada.Text_IO.put (Ada.Command_Line.Argument (i));
end if;
k := k / 2; -- we go to the next bit of "set"
end loop;
Ada.Text_IO.put_line("}");
end print_subset;
begin
for i in 0..2**Ada.Command_Line.Argument_Count-1 loop
print_subset (i);
end loop;
end powerset;
</lang>
 
 
{{out}}
 
<pre>>./powerset a b c d
{}
{a}
{b}
{a,b}
{c}
{a,c}
{b,c}
{a,b,c}
{d}
{a,d}
{b,d}
{a,b,d}
{c,d}
{a,c,d}
{b,c,d}
{a,b,c,d}</pre>
 
=={{header|ALGOL 68}}==
Anonymous user