Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers | Function to generate a permutation of integers from 1 to N such that the absolute difference of all the two consecutive integers give K distinct integers ; To store the permutation ; For sequence 1 2 3. . . ; For sequence N , N - 1 , N - 2. . . ; Flag is used to alternate between the above if else statements ; If last element added was r + 1 ; If last element added was l - 1 ; Print the permutation ; Driver code
def printPermutation ( N , K ) : NEW_LINE INDENT res = list ( ) ; NEW_LINE l , r , flag = 1 , N , 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT if flag == False : NEW_LINE INDENT res . append ( l ) NEW_LINE l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res . append ( r ) ; NEW_LINE r -= 1 ; NEW_LINE DEDENT flag = flag ^ 1 ; NEW_LINE DEDENT if flag == False : NEW_LINE INDENT for i in range ( r , 2 , - 1 ) : NEW_LINE INDENT res . append ( i ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( l , r ) : NEW_LINE INDENT res . append ( i ) NEW_LINE DEDENT DEDENT for i in res : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT N , K = 10 , 4 NEW_LINE printPermutation ( N , K ) NEW_LINE