Permutations of an array having sum of Bitwise AND of adjacent elements at least K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPermutation ( int arr [ ] , int n , int k ) { bool flag = false ; sort ( arr , arr + n ) ; 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 ++ ) { cout << arr [ i ] << " ▁ " ; } cout << " STRNEWLINE " ; } } while ( next_permutation ( arr , arr + n ) ) ; if ( flag == false ) { cout << " - 1" ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int K = 8 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPermutation ( arr , N , K ) ; return 0 ; }