Permutations: Difference between revisions

m
(Fixed lazy D version)
Line 123:
-- print all permutations of 1 .. n
-- where n is given as a command line argument
-- to compile with gnatGNAT : gnatmakegnat make perm.adb
-- to call on command line : perm n
with adaAda.text_ioText_IO, adaAda.command_lineCommand_Line;
 
procedure permPerm is
use adaAda.text_ioText_IO, adaAda.command_lineCommand_Line;
nN : integerInteger;
begin
if argument_countArgument_Count /= 1
then
put_linePut_Line (command_nameCommand_Name & " n (with n >= 1)");
return;
else
nN := integerInteger'valueValue (argumentArgument (1));
end if;
declare
subtype elementElement is integerInteger range 1 .. nN;
type permutationPermutation is array (elementElement'rangeRange) of elementElement;
pP : permutationPermutation;
is_lastIs_Last : booleanBoolean := falseFalse;
procedure Swap (A, B : in out Integer) is
pC (j): Integer := tA;
begin
jA := j + 1B;
kB := k - 1C;
end;
-- compute next permutation in lexicographic order
Line 151 ⟶ 158:
-- exchange the element x preceding the tail, with the minimum value in the tail,
-- that is also greater than x
procedure nextNext is
iI, jJ, k, tK : elementElement;
begin
-- find longest tail decreasing sequence
Line 158 ⟶ 165:
-- and the ith element will be exchanged later
-- with some element of the tail
is_lastIs_Last := trueTrue;
iI := nN - 1;
loop
if pP (iI) < pP (iI+1)
then
is_lastIs_Last := falseFalse;
exit;
end if;
Line 169 ⟶ 176:
-- next instruction will raise an exception if i = 1, so
-- exit now (this is the last permutation)
exit when iI = 1;
iI := iI - 1;
end loop;
-- if all the elements of the permutation are in
-- decreasing order, this is the last one
if is_lastIs_Last then
return;
end if;
-- sort the tail, i.e. reverse it, since it is in decreasing order
jJ := iI + 1;
kK := nN;
while jJ < kK loop
tSwap :=(P (J), pP (jK));
p (j)J := pJ + (k)1;
p (k)K := tK - 1;
j := j + 1;
k := k - 1;
end loop;
-- find lowest element in the tail greater than the ith element
jJ := nN;
while pP (jJ) > pP (iI) loop
jJ := jJ - 1;
end loop;
jJ := jJ + 1;
-- exchange them
-- this will give the next permutation in lexicographic order,
-- since every element from ith to the last is minimum
tSwap :=(P (I), pP (iJ));
p (i) := p (j);
p (j) := t;
end next;
procedure printPrint is
begin
for iI in elementElement'rangeRange loop
putPut (integerInteger'imageImage (pP (iI)));
end loop;
new_lineNew_Line;
end printPrint;
-- initialize the permutation
procedure initInit is
begin
for iI in elementElement'rangeRange loop
pP (iI) := iI;
end loop;
end initInit;
 
begin
initInit;
while not Is_Last loop
printPrint;
nextNext;
exit when is_last;
end loop;
end;
end permPerm;</lang>
 
=={{header|ALGOL 68}}==
Anonymous user