7017
|
1 ## Copyright (C) 2001, 2006, 2007 Paul Kienzle |
5827
|
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 |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
5827
|
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 |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5827
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {} perms (@var{v}) |
|
21 ## |
|
22 ## Generate all permutations of @var{v}, one row per permutation. The |
|
23 ## result has size @code{factorial (@var{n}) * @var{n}}, where @var{n} |
|
24 ## is the length of @var{v}. |
|
25 ## |
6754
|
26 ## As an example, @code{perms([1, 2, 3])} returns the matrix |
|
27 ## @example |
|
28 ## 1 2 3 |
|
29 ## 2 1 3 |
|
30 ## 1 3 2 |
|
31 ## 2 3 1 |
|
32 ## 3 1 2 |
|
33 ## 3 2 1 |
|
34 ## @end example |
5827
|
35 ## @end deftypefn |
|
36 |
|
37 function A = perms (v) |
6391
|
38 if (nargin != 1) |
|
39 print_usage (); |
|
40 endif |
5827
|
41 v = v(:); |
|
42 n = length (v); |
|
43 if (n == 1) |
|
44 A = v; |
|
45 else |
|
46 B = perms (v(1:n-1)); |
|
47 Bidx = 1:size (B, 1); |
|
48 A = v(n) * ones (prod (2:n), n); |
|
49 A(Bidx,1:n-1) = B; |
|
50 k = size (B, 1); |
|
51 for i = n-1:-1:2 |
|
52 A(k+Bidx,1:i-1) = B(Bidx,1:i-1); |
|
53 A(k+Bidx,i+1:n) = B(Bidx,i:n-1); |
|
54 k = k + size (B, 1); |
|
55 endfor |
|
56 A(k+Bidx,2:n) = B; |
|
57 endif |
|
58 endfunction |