Number of unique triplets whose XOR is zero | CPP program to count the number of unique triplets whose XOR is 0 ; function to count the number of unique triplets whose xor is 0 ; To store values that are present ; stores the count of unique triplets ; traverse for all i , j pairs such that j > i ; xor of a [ i ] and a [ j ] ; if xr of two numbers is present , then increase the count ; returns answer ; Driver code to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int a [ ] , int n ) { unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) s . insert ( a [ i ] ) ; int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int xr = a [ i ] ^ a [ j ] ; if ( s . find ( xr ) != s . end ( ) && xr != a [ i ] && xr != a [ j ] ) count ++ ; } } return count / 3 ; } int main ( ) { int a [ ] = { 1 , 3 , 5 , 10 , 14 , 15 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countTriplets ( a , n ) ; return 0 ; }