Permutations of an array having sum of Bitwise AND of adjacent elements at least K | 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
function printPermutation ( arr , n , k ) { let flag = false ; arr . sort ( ) ; do { let sum = 0 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { sum += arr [ i ] & arr [ i + 1 ] ; } if ( sum >= k ) { flag = true ; for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; } document . write ( " " ) ; } } while ( next_permutation ( arr ) ) ; if ( flag == false ) { System . out . print ( " " ) ; } } function next_permutation ( p ) { for ( let a = p . length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( let b = p . length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { let 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 ; } let arr = [ 1 , 2 , 3 , 4 , 5 ] ; let K = 8 ; let N = arr . length ; printPermutation ( arr , N , K ) ;