EularProject 24: 排列组合的序数问题

Lexicographic permutations

Problem 24

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012   021   102   120   201   210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?


Answer:
2783915460
Completed on Wed, 4 Feb 2015, 15:13

Go to the thread for problem 24 in the forum.

Python code:

def func1(x):
    i=1
    val=1
    while val<x:
        i+=1
        val*=i
    if val==x:
        return (1,i,0)
    else:
        step=val//i
        k=x//step
        return (k,i-1,x%(k*step))

def func2(x):
    lst=[]
    result=func1(x)
    while result[2]!=0:
        lst.append(result[0:2])
        result=func1(result[2])
    lst.append(result[0:2])
    return lst

def func3(x,clst):
    result=[]
    count=len(clst)
    lst=func2(x)
    length=len(lst)
    for i in range(0,length):
        if i<length-1:
            delta=lst[i][0]
            position=lst[i][1]+1
            while count>position:
                result.append(clst[-count])
                del clst[-count]
                count-=1
            result.append(clst[-position+delta])
            del clst[-position+delta]
            count-=1
        else:
            delta=lst[i][0]-1
            position=lst[i][1]+1
            while count>position:
                result.append(clst[-count])
                del clst[-count]
                count-=1
            result.append(clst[-position+delta])
            del clst[-position+delta]
            count-=1
            while count>0:
                result.append(clst[-1])
                del clst[-1]
                count-=1
    return result
            
charlist=[0,1,2,3,4,5,6,7,8,9]
k=120
print(func2(k))
print(func3(k,charlist))


time: <1s

代码注释参考http://blog.csdn.net/zhangzhengyi03539/article/details/47057049

------------------
祝身体健康,万事如意

华电北风吹

天津大学计算机科学与技术学院

天津市卫津路92号

邮编: 300072

邮箱: [email protected]

你可能感兴趣的:(EularProject 24: 排列组合的序数问题)