"""
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 -> 1,3,2
3,2,1 -> 1,2,3
1,1,5 -> 1,5,1
"""

import time


def next_lexicographic_permutation(lst):
    sep = len(lst) - 2
    while sep >= 0 and lst[sep] > lst[sep + 1]:
        sep -= 1

    to_swap = len(lst) - 1
    while lst[sep] > lst[to_swap]:
        to_swap -= 1

    swap(lst, sep, to_swap)
    invert(lst, sep + 1, len(lst))
    return lst


def invert(arr, lo, hi):
    while lo < hi:
        swap(arr, lo, hi - 1)
        lo += 1
        hi -= 1


def swap(arr, lo, hi):
    tmp = arr[lo]
    arr[lo] = arr[hi]
    arr[hi] = tmp


if __name__ == '__main__':
    arr = [1, 5, 8, 4, 7, 6, 5, 3, 1]
    while True:
        print arr
        arr = next_lexicographic_permutation(arr)
        time.sleep(1)
