Lexicographic permutations

248 阅读1分钟

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?

思路:从最高位开始,最高位0,1,2,3,每个选择都有10!/10种可能,那就1000000/(factorial(10)/10)可以确定选第几个数字,迭代获取每一位的数字,要注意我们这样获取的是第999999位数字,所以,除数要+1

代码:swift

        var c:Double = 1000000+1
        var arr:Array = [0,1,2,3,4,5,6,7,8,9]
        var dic:[Int:Int] = [:]
        for i in 0...9 {
            let jiechen = self.jiechen(10-i)/Double(10-i)
            let index = Int(c/jiechen)
            dic[9-i] = arr[index]
            arr.remove(at: index)
            let ddd = c.truncatingRemainder(dividingBy: jiechen)
            print(i)
            c = ddd
        }
        print(dic)
        var numArray:Array<Int>=[]
        for i in 0...9 {
            numArray.insert(dic[i]!, at: 0)
        }
        print(numArray)

projecteuler.net/problem=24