5827
|
1 ## Copyright (C) 2001 Paul Kienzle |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
|
19 |
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {} perms (@var{v}) |
|
22 ## |
|
23 ## Generate all permutations of @var{v}, one row per permutation. The |
|
24 ## result has size @code{factorial (@var{n}) * @var{n}}, where @var{n} |
|
25 ## is the length of @var{v}. |
|
26 ## |
|
27 ## @end deftypefn |
|
28 |
|
29 function A = perms (v) |
6391
|
30 if (nargin != 1) |
|
31 print_usage (); |
|
32 endif |
5827
|
33 v = v(:); |
|
34 n = length (v); |
|
35 if (n == 1) |
|
36 A = v; |
|
37 else |
|
38 B = perms (v(1:n-1)); |
|
39 Bidx = 1:size (B, 1); |
|
40 A = v(n) * ones (prod (2:n), n); |
|
41 A(Bidx,1:n-1) = B; |
|
42 k = size (B, 1); |
|
43 for i = n-1:-1:2 |
|
44 A(k+Bidx,1:i-1) = B(Bidx,1:i-1); |
|
45 A(k+Bidx,i+1:n) = B(Bidx,i:n-1); |
|
46 k = k + size (B, 1); |
|
47 endfor |
|
48 A(k+Bidx,2:n) = B; |
|
49 endif |
|
50 endfunction |