Reputation: 29285
Suppose I have a vector of integers like this:
A = [1 2 3]
What I need is nth permutation of vector A
. As we now a vector of n
numbers has n!
permutation, For example some permutation of A
is:
[1 2 3]
[1 3 2]
[2 1 3]
[2 3 1]
...
Is there any built-in function for calculating nth permutation? if not, can anyone please offer me a efficient algorithm for calculate it? Any suggestion would be highly appreciated
Upvotes: 0
Views: 596
Reputation: 699
If you like doing stuff in less lines of code, you can also do:
A=1:N;
nthPerm=getfield(perms(A),{n,A})
Note that this is only valid if A=1,2,3,...,N
. For different values of A
, you would have to change this into:
A=1:N;
nthPerm=getfield(perms(A),{n,1:length(A)})
Upvotes: 0
Reputation: 29285
I found my answer from @Divakar comment (special thanks to @Divakar)
What I need is:
% this my vector 1, 2, 3 , ..., N
A = 1 : N;
P = perms(A);
% nth permutation of A is nth row of P
nthPerm = P(n, :);
Upvotes: 1
Reputation: 245
perms(v) works for the n! case,
http://www.mathworks.de/matlabcentral/fileexchange/11462-npermutek/content/npermutek.m works for the n^n or n^k case.
Upvotes: 0
Reputation: 8391
If A
is just the trivial sequence 1:N
, as @Divakar said, the command
perms(1:N)
produces the permutations you need.
If A
is an array whose content is generic and whose length is N
, perms
can be used to obtain the indices allowing the permutations, i.e.
A_permutations = A(perms(1:N))
Example:
given
A =
3 7 9
A(perms(1:3))
9 7 3
9 3 7
7 9 3
7 3 9
3 7 9
3 9 7
Upvotes: 0