home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C!T ROM 2
/
ctrom_ii_b.zip
/
ctrom_ii_b
/
PROGRAM
/
PASCAL
/
PARADIS1
/
PERM.PAS
< prev
next >
Wrap
Pascal/Delphi Source File
|
1992-02-06
|
3KB
|
80 lines
(4174) Sun 2 Feb 92 2:10
By: Mitch Davis
To: Trevor Carlsen and Frank Masingill
Re: Sets
St:
---------------------------------------------------------------------------
@MSGID: 3:634/384.6 21020ed4
> FM> ...That will ask a user to enter 4 alpha characters, then take the
> FM> four characters and display them back in all 24 combinations.
> FM> begin
> FM> write('Enter 4 characters and press enter: '); readln(st);
> FM> for w := 1 to 4 do
> FM> for x := 1 to 4 do
> FM> for y := 1 to 4 do
> FM> for z := 1 to 4 do
> FM> begin
> FM> s := [w,x,y,z]; {create a set}
> FM> if byte(s) = 30 then {all 4 bits 1..4 are set}
> FM> writeln(st[w],st[x],st[y],st[z]);
> FM> end;
> FM> readln
> FM> end.
etc. YUCK! What happens if you want to expand or shrink it?
A FAR nicer way is (tested):
-- 8< -----------------------------------------------------
program ShowPerms;
const digits = 4; {How many digits to permute: n digits = n! perms}
var PermArray:array [1..digits] of byte; {Permutation holder}
ThisDigit:integer;
procedure writePerm; var loop:byte;
begin for loop := 1 to digits do write (PermArray [loop]); writeln; end;
procedure PermuteAtLevel (Level:integer);
var loop:integer;
begin
inc (ThisDigit); PermArray [Level] := ThisDigit;
if ThisDigit = digits then writeperm; {If we've accounted for all digits}
for loop := 1 to digits do if PermArray [loop] = 0
then PermuteAtLevel (loop);
dec (ThisDigit); PermArray [Level] := 0;
end;
begin
ThisDigit := -1; {Left of Left-hand-side}
Fillchar (PermArray,sizeof (PermArray),#0); {Make it zeroes}
PermuteAtLevel (0); {Start at the bottom}
end.
This works for any level, although you might wait a while for the higher
numbers (eg Digits = 16 = 16! perms > 2^50!). It is very efficient compared to
the algorithm you've been studying. This problem is one which can be easily
solved with graph theory.
I used "Algorithms" p628 by Robert Sedgewick as my starting point. If you
don't yet have an algorithm cookbook, then I _thoroughly_ recommend this book
(also available for C). There are very few algorithms NOT in it. ISBN
0-201-06673-4.
BTW, the original question called for perms of characters. Read in a 4
character string, then replace the write in WritePerm with:
write (MyString [PermArray [loop]]);
To spec!
Mitch.
--- FD 1.99c
* Origin: Point Mitch: Daddy, stop the car! I'm going to be .. (3:634/384.6)
@PATH: 634/384 640/821 209/209 13/13 396/1 170/400 512/0 1007