Permutations of an array having sum of Bitwise AND of adjacent elements at least K | Python3 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
def next_permutation ( a ) : NEW_LINE INDENT for i in reversed ( range ( len ( a ) - 1 ) ) : NEW_LINE INDENT if a [ i ] < a [ i + 1 ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT j = next ( j for j in reversed ( range ( i + 1 , len ( a ) ) ) if a [ i ] < a [ j ] ) NEW_LINE a [ i ] , a [ j ] = a [ j ] , a [ i ] NEW_LINE a [ i + 1 : ] = reversed ( a [ i + 1 : ] ) NEW_LINE return True NEW_LINE DEDENT def printPermutation ( arr , n , k ) : NEW_LINE INDENT flag = False NEW_LINE arr . sort ( ) NEW_LINE while True : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT sum += arr [ i ] & arr [ i + 1 ] NEW_LINE DEDENT if ( sum >= k ) : NEW_LINE INDENT flag = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if ( next_permutation ( arr ) == False ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE K = 8 NEW_LINE N = len ( arr ) NEW_LINE printPermutation ( arr , N , K ) NEW_LINE