Newsgroups: comp.lang.apl
Path: watmath!watserv1!utgpu!cs.utexas.edu!qt.cs.utexas.edu!zaphod.mps.ohio-state.edu!uunet.ca!geac!itcyyz!yrloc!hui
From: hui@yrloc.ipsa.reuter.COM (Roger Hui)
Subject: Permutations
Message-ID: <1992Mar31.225807.28993@yrloc.ipsa.reuter.COM>
Organization: Iverson Software Inc.
Date: Tue, 31 Mar 92 22:58:07 GMT
Lines: 59


Given n, compute the ((!n),n) matrix of all                   perm 3
permutations of i.n, in ascending order.                   0 1 2
                                                           0 2 1
These are restatements in J of ideas in:                   1 0 2
"Some Uses of { and }", APL87 Conference Proceedings.      1 2 0
"The N Queens Problem", APL Quote-Quad, 1981 3.            2 0 1
                                                           2 1 0
 
perm0 =. i.@! A. i.
 
perm1 =. (#~ i.@{:@$ -:"1 /:~"1) @ (#~ #: i.@^~)
 
perm2 =. (,:@$&0)`(i. ,/@(,"1"_1) $:@<: {"2 1 -."1 0~@i.) @. (1&<)
 
seed  =. 1 0&$
ni    =. i.@>:@{:@$
grow  =. ni ,/@(,"1"_1) ] {"2 1 -."1 0~@ni
perm3 =. [ grow@]^:(>{:@$) seed
 
perm4 =. 'grow^:y.i.1 0' : ''
 
t=.0 0$''
t=.t, '$.=.1+1<y.'
t=.t, ',:y.$0'
t=.t, ',/(i.y.),"1"_1(perm5<:y.){"2 1-."1 0~i.y.'
perm5 =. t : ''
 
perm0 exploits the fact that the primitive A. does almost exactly
what is required.
 
perm1 generates all n-tuples of i.n (0 0 0, 0 0 1, 0 0 2, 0 1 0, etc.)
and then selects the permutations contained therein.  It requires space
(and time) exponential in the size of the result.
 
perm2 is recursive:  the rows in  perm n  whose first element is k,
are formed by prefacing k to the result of permuting (i.n)-.k by perm n-1.
 
perm3 uses the same idea as perm2, but replaces recursion by tacit ^: .
 
perm4 uses the same idea as perm2, but replaces recursion by explicit ^: .
(perm n) = grow grow ... grow i.1 0
 
perm5 uses the same idea as perm2, but replaces tacit recursion by
explicit recursion.
 
The same general strategy can be used to generate the following
combinatorial objects:
 
. all size m combinations of i.n
. all size m compositions of i.n
. all self-upgrading permutations of i.n
. all self-downgrading permutations of i.n
. all size m partitions of n
. all partitions of n

------------------------------------
Roger Hui, Iverson Software Inc., 33 Major Street, Toronto, Ontario  M5S 2K9
Phone: (416) 925 6096;  Fax: (416) 488 7559
