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 ## |
6754
|
27 ## As an example, @code{perms([1, 2, 3])} returns the matrix |
|
28 ## @example |
|
29 ## 1 2 3 |
|
30 ## 2 1 3 |
|
31 ## 1 3 2 |
|
32 ## 2 3 1 |
|
33 ## 3 1 2 |
|
34 ## 3 2 1 |
|
35 ## @end example |
5827
|
36 ## @end deftypefn |
|
37 |
|
38 function A = perms (v) |
6391
|
39 if (nargin != 1) |
|
40 print_usage (); |
|
41 endif |
5827
|
42 v = v(:); |
|
43 n = length (v); |
|
44 if (n == 1) |
|
45 A = v; |
|
46 else |
|
47 B = perms (v(1:n-1)); |
|
48 Bidx = 1:size (B, 1); |
|
49 A = v(n) * ones (prod (2:n), n); |
|
50 A(Bidx,1:n-1) = B; |
|
51 k = size (B, 1); |
|
52 for i = n-1:-1:2 |
|
53 A(k+Bidx,1:i-1) = B(Bidx,1:i-1); |
|
54 A(k+Bidx,i+1:n) = B(Bidx,i:n-1); |
|
55 k = k + size (B, 1); |
|
56 endfor |
|
57 A(k+Bidx,2:n) = B; |
|
58 endif |
|
59 endfunction |