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
function printPermutation ( N , K ) { var res = [ ] ; var l = 1 , r = N , flag = 0 ; for ( var i = 0 ; i < K ; i ++ ) { if ( ! flag ) { res . push ( l ) ; l ++ ; } else { res . push ( r ) ; r -- ; } flag ^= 1 ; } if ( ! flag ) { for ( var i = r ; i >= l ; i -- ) res . push ( i ) ; } else { for ( var i = l ; i <= r ; i ++ ) res . push ( i ) ; } for ( var i = 0 ; i < res . length ; i ++ ) { document . write ( res [ i ] + " " ) ; } } var N = 10 , K = 4 ; printPermutation ( N , K ) ;