Computing the nth 6 character permutation of an alphabet

流过昼夜 提交于 2019-12-04 07:48:41

What you are looking is called unrank in combinatorial algorithm. Consider the list of the element of a set S in a fixed order, unrank_S(i) returns the i-th element of the list without computing the list. So your S here is Perm(n, k) : the list of all k-permutation of a set of size n. As you know the size of this set is n!/k!. One way to do that is to use Factoradic numbers

Here is an unrank algorithm in python:

def factorial(n):
    if n == 0: return 1
    return n*factorial(n-1)

def unrank(S, k, i):
    S = list(S)   # make a copy to avoid destroying the list
    n = len(S)
    nb = factorial(n) // factorial(n-k)
    if i >= nb:
        raise IndexError
    res = []
    while k > 0:
        nb = nb // n
        pos = i // nb   # the factoradic digits
        i = i % nb      # the remaining digits
        res.append(S[pos])
        del S[pos]
        k = k-1
        n = n-1
    return res

Then

[unrank(range(5), 2, i) for i in range(20)]
 [[0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 4], [4, 0], [4, 1], [4, 2], [4, 3]]

and

unrank(list('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'),6, 128347238)\
['G', 'L', 'E', 'H', 'T', 'R']

Of course you might want to compute factorial using a better method or even to cache it in a pre-computed array to avoid recomputing it.

I don't have much time to give you complete solution but following idea can provide some line to think on.

You need to find Nth permutation taking 6 characters at a time.
Lets fix first place character. Then there remains 25 other characters.
Total number of permutations from remaining characters is P = 25C5 * 5!.

So with A as first character, you can have P permutations. If P is less than N, then A can't be at first place.

Now keep B at first place and total numbers of permutations till B at first place are 2*P.

Say you keep Kth character at first place so that total number of permutations till Kth character are K*P, with K*P less than N, and after keeping K+1th character, (K+1)*P, exceeds N. So your required string need to have K+1th character at first place.

So you have to find N-K*P remaining permutations. with remaining 25 characters and 5 places. So same problem is reduced to 1 character less, 1 place less and lesser number of more permutations to find.
So solve in similar way for all places.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!