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
< ? php function printPermutation ( $ N , $ K ) { $ res = array ( ) ; $ l = 1 ; $ r = $ N ; $ flag = 0 ; for ( $ i = 0 ; $ i < $ K ; $ i ++ ) { if ( ! $ flag ) { array_push ( $ res , $ l ) ; $ l ++ ; } else { array_push ( $ res , $ r ) ; $ r -- ; } $ flag ^= 1 ; } if ( ! $ flag ) { for ( $ i = $ r ; $ i >= $ l ; $ i -- ) array_push ( $ res , $ i ) ; } else { for ( $ i = l ; $ i <= $ r ; $ i ++ ) array_push ( $ res , $ i ) ; } for ( $ i = 0 ; $ i < sizeof ( $ res ) ; $ i ++ ) echo $ res [ $ i ] , " ▁ " ; } $ N = 10 ; $ K = 4 ; printPermutation ( $ N , $ K ) ; ? >