Permutations of an array having sum of Bitwise AND of adjacent elements at least K | Java program for the above approach ; Function to print all permutations of arr [ ] such that the sum of Bitwise AND of all adjacent element is at least K ; To check if any permutation exists or not ; Sort the given array ; Find all possible permutations ; Stores the sum of bitwise AND of adjacent elements of the current permutation ; Traverse the current permutation of arr [ ] ; Update the sum ; If the sum is at least K , then print the current permutation ; Set the flag variable ; Print the current permutation ; If flag is unset , then print - 1 ; Driver Code ; Function Call
import java . util . * ; class GFG { static void printPermutation ( int arr [ ] , int n , int k ) { boolean flag = false ; Arrays . sort ( arr ) ; do { int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { sum += arr [ i ] & arr [ i + 1 ] ; } if ( sum >= k ) { flag = true ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . print ( "NEW_LINE"); } } while ( next_permutation ( arr ) ) ; if ( flag == false ) { System . out . print ( " - 1" ) ; } } static boolean next_permutation ( int [ ] p ) { for ( int a = p . length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int K = 8 ; int N = arr . length ; printPermutation ( arr , N , K ) ; } }