nthperm(p)
nthperm(p)
Return the k
that generated permutation p
. Note that nthperm(nthperm([1:n], k)) == k
for 1 <= k <= factorial(n)
.
Examples
In the Julia programming language, the function nthperm(v, k)
computes the kth lexicographic permutation of a vector v
.
julia> nthperm([1, 2, 3], 2)
3-element Array{Int64,1}:
1
3
2
Here are some common examples of its use:
-
Generate the first lexicographic permutation:
julia> nthperm([4, 2, 3], 1) 3-element Array{Int64,1}: 4 2 3
This example generates the first lexicographic permutation of the vector
[4, 2, 3]
. -
Find the 5th lexicographic permutation:
julia> nthperm([1, 2, 3], 5) 3-element Array{Int64,1}: 2 3 1
It computes the 5th lexicographic permutation of the vector
[1, 2, 3]
. - Compute a permutation of a string:
julia> nthperm("abc", 2) 3-element Array{Char,1}: 'a' 'c' 'b'
This example demonstrates how
nthperm
works with a string input.
Common mistake example:
julia> nthperm([1, 2, 3], 7)
ERROR: ArgumentError: k (7) is greater than the number of permutations (6)
In this example, the value of k
provided is greater than the total number of possible permutations for the given vector. It's important to ensure that k
is within the valid range of permutations for the vector v
to avoid such errors.
See Also
User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.