c++ - Efficiently calculate index of specific element in lexicographical ordering -
i have 4 elements:
a b c d i can arrange permutations of n elements in lexicographical ordering, n=2:
0=aa 1=ab 2=ac 3=ad ... 15=dd how can i, without resorting counting, calculate index in ordering specific element?
when enumerate elements 0=a 1=b 2=c 3=d , have string string can calculate index n=2
4 * val(string[0]) + val(string[1]) string="ac" -> 4*0 + 2 = 2 string="dd" -> 4*3 + 3 = 15 how can find index string , n > 2? need n=2,3,4,5, feels there should general solution not seeing?
isn't just
(4 ^ (n - 1)) * val(string[0]) + (4 ^ (n - 2)) * val(string[1]) + ... + (4 ^ (0)) * val(string[n-1]) you'd program loop.
Comments
Post a Comment