Find the Number of Permutations that satisfy the given condition in an array | C ++ program to find the number of permutations that satisfy the given condition in an array ; Function to calculate x ^ y recursively ; Function to return the number of permutations that satisfy the given condition in an array ; If there is only one element then only one permutation is available ; Sort the array for calculating the number of elements occurring twice ; If the maximum element is occurring twice , then the number of permutations satisfying the condition is 0 ; This variable will store the number of element occurring twice ; Loop to check the number of elements occurring twice ; Check if this element is occurring twice ; If this element is occurring twice then check if this number is occurring more than twice ; If element occurring thrice then no permutation will satisfy the given condition ; Since we have checked the next element as well , then we can increment the loop variable ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pow ( int x , int y ) { if ( y == 1 ) return x ; if ( y == 0 ) return 1 ; int temp = pow ( x , y / 2 ) ; temp *= temp ; if ( y & 1 ) temp *= x ; return temp ; } int noOfPermutations ( int * a , int n ) { if ( n == 1 ) { return 1 ; } sort ( a , a + n ) ; if ( a [ n - 1 ] == a [ n - 2 ] ) { return 0 ; } int x = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { if ( a [ i ] == a [ i + 1 ] ) { if ( a [ i ] == a [ i + 2 ] ) { return 0 ; } x ++ ; i ++ ; } } return pow ( 2 , n - 2 * x - 1 ) ; } int main ( ) { int a [ ] = { 1 , 2 , 2 , 3 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int num = noOfPermutations ( a , n ) ; cout << num ; return 0 ; }