# Euler Problem 24¶

Back to overview.

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?

I tried to solve this by thinking and failed to be hones. So we implement a generator and get the millionth element.

In [19]:

    from collections import deque

    def permutation_generator(xs):
        if not xs:
            yield deque()
        r = []
        for i in range(len(xs)):
            x = xs[i]
            ys = permutation_generator(xs[:i] + xs[i+1:])
            for y in ys:
                y.appendleft(x)
                yield y
        raise StopIteration

    assert(list(map(lambda s: "".join(s), permutation_generator("012"))) == ['012', '021', '102', '120', '201', '210'])

All right, now we reuse the function to get the nth element from problem 7 and give ourselves a solution.

In [26]:

    def get_nth(generator, n):
        import itertools
        return next(itertools.islice(generator, n - 1, n))

    ps = permutation_generator("0123456789")
    s = int("".join(get_nth(ps, 1000000)))
    assert(s == 2783915460)
    print(s)

    2783915460