Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers | Java implementation of the above approach ; 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
import java . util . Vector ; class GFG { static void printPermutation ( int N , int K ) { Vector < Integer > res = new Vector < > ( ) ; int l = 1 , r = N , flag = 0 ; for ( int i = 0 ; i < K ; i ++ ) { if ( flag == 0 ) { res . add ( l ) ; l ++ ; } else { res . add ( r ) ; r -- ; } flag ^= 1 ; } if ( flag != 1 ) { for ( int i = r ; i >= l ; i -- ) { res . add ( i ) ; } } else { for ( int i = l ; i <= r ; i ++ ) { res . add ( i ) ; } } for ( Integer i : res ) { System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 10 , K = 4 ; printPermutation ( N , K ) ; } }