Inverse permutation index
Mathematica, 74 bytes
Max@k[i,Flatten@Outer[i=Permutations[j=Range@#];k=Position,{i[[#]]},j,1]]&
Uses 1-indexing. Very inefficient. (uses ~11GB of memory when the input is 11
)
Explanation
j=Range@#
Generate a list from 1 to N. Store that in j
.
i=Permutations[...]
Find all permutations of j
. Store that in i
.
k=Position
Store the Position
function in k
. (to reduce byte-count when using Position
again)
Flatten@Outer[...,{i[[#]]},j,1]
Find the inverse permutation of the N-th permutation.
Max@k[i,...]
Find the k
(Position
) of the inverse permutation in i
(all permutations)
Using built-ins, 46 43 bytes
a[(a=Ordering)/@Permutations@Range@#][[#]]&
1-indexed.
05AB1E, 14 13 bytes
Very memory inefficient. Now even more memory inefficient (but 1 byte shorter).
0-based range.
Uses CP-1252 encoding.
ƒ¹ÝœD¹èNkˆ}¯k
Try it online! or as a Modified test suite
Explanation
ƒ # for N in range[0 .. x]
¹ÝœD # generate 2 copies of all permutations of range[0 .. x]
¹è # get permutation at index x
Nkˆ # store index of N in that permutation in global list
} # end loop
¯k # get index of global list (inverse) in list of permutations
Jelly, 6 bytes
ịŒ!⁺iR
I/O uses 1-based indexing. Very slow and memory-hungry.
Verification
As long as the input does not exceed 8! = 40320, it is sufficient to consider all permutations of the array [1, …, 8]. For the last test case, the permutations of [1, …, 9] suffice.
With slightly modified code that only considers the permutations of the first 8 or 9 positive integers, you can Try it online! or verify all remaining test cases.
How it works
ịŒ!⁺iR Main link. Argument: n
Œ! Yield all permutations of [1, ..., n].
ị At-index; retrieve the n-th permutation.
⁺ Duplicate the Œ! atom, generating all permutations of the n-th permutation.
R Range; yield [1, ..., n].
i Index; find the index of [1, ..., n] in the generated 2D array.
Alternate approach, 6 bytes (invalid)
Œ!Ụ€Ụi
It's just as long and it uses the forbidden grade up atom Ụ
, but it's (arguably) more idiomatic.
By prepending 8 (or 9 for the last test case), we can actually Try it online!
How it works
Œ!Ụ€Ụi Main link. Argument: n
Œ! Yield all permutations of [1, ..., n].
Ụ€ Grade up each; sort the indices of each permutation by the corresponding
values. For a permutation of [1, ..., n], this inverts the permutation.
Ụ Grade up; sort [1, ..., n!] by the corresponding inverted permutations
(lexicographical order).
i Index; yield the 1-based index of n, which corresponds to the inverse of
the n-th permutation.