I have a somewhat unusual question, that may or may not have been asked before (I did not find anything though, however I might just have looked for the wrong buzzwords).
I think you are dealing with the rank of a permutation here. (I could be wrong).
I have written a Rosetta code task on this; as well as answering other SO questions on this here and here.