Saturday, October 7, 2017

The Next Permutation

Lexicographic

ACM 2009 / Greater NY Programming Contest

Problem E: The Next Permutation

http://acmgnyr.org/year2009/e.pdf

In [1]:
# The following algorithm generates the next permutation lexicographically after a given permutation. 
# It changes the given permutation in-place.
#
# 1. Find the largest index k such that a[k] < a[k + 1]. 
#    If no such index exists, the permutation is the last permutation.
# 2. Find the largest index l greater than k such that a[k] < a[l].
# 3. Swap the value of a[k] with that of a[l].
# 4. Reverse the sequence from a[k + 1] up to and including the final element a[n].

def next_lex(a):
    k = len(a)-2
    while (k >= 0 and a[k] >= a[k+1]):
        k -= 1

    if k < 0:
        return False  # Biggest 
    
    l = len(a)-1
    while (a[l] <= a[k]):
        l -= 1
        
    a[k], a[l] = a[l], a[k]
    a[k+1:] = a[k+1:][::-1]
    return True
In [2]:
# hardcoded test data
nums = [123,279134399742,987]

for n in nums:
    print(n, end=" -> ")
    sn=str(n)
    l1=list(sn)
    if (next_lex(l1)):
        x="".join(x for x in l1)
        print(x)
    else:
        print("BIGGEST")
123 -> 132
279134399742 -> 279134423799
987 -> BIGGEST