Generate a circular permutation with number of mismatching bits between pairs of adjacent elements exactly 1 | Java program for the above approach ; Function to find the permutation of integers from a given range such that number of mismatching bits between pairs of adjacent elements is 1 ; Initialize an arrayList to store the resultant permutation ; Store the index of rotation ; Iterate over the range [ 0 , N - 1 ] ; Traverse all the array elements up to ( 2 ^ k ) - th index in reverse ; If current element is S ; Check if S is zero ; Rotate the array by index value to the left ; Driver Code
import java . io . * ; import java . util . * ; class GFG { public static List < Integer > circularPermutation ( int n , int start ) { List < Integer > res = new ArrayList < > ( List . of ( 0 ) ) , ret = new ArrayList < > ( ) ; int index = - 1 ; for ( int k = 0 , add = 1 << k ; k < n ; k ++ , add = 1 << k ) { for ( int i = res . size ( ) - 1 ; i >= 0 ; i -- ) { if ( res . get ( i ) + add == start ) index = res . size ( ) ; res . add ( res . get ( i ) + add ) ; } } if ( start == 0 ) return res ; while ( ret . size ( ) < res . size ( ) ) { ret . add ( res . get ( index ) ) ; index = ( index + 1 ) % res . size ( ) ; } return ret ; } public static void main ( String [ ] args ) { int N = 2 , S = 3 ; System . out . println ( circularPermutation ( N , S ) ) ; } }