Count pairs with bitwise OR less than Max in C++

C++Server Side ProgrammingProgramming

We are given an integer array and the task is to count the total number of pairs that can be formed using the given array values such that the OR operation on the pairs will result in the value less than MAX value in the given pair.

The truth table for OR operation is given below

ABAVB
000
101
011
111

Input − int arr[] = {2, 5, 1, 8, 9}

Output − Count of pairs with bitwise OR less than Max are − 3

Explanation

XYX V Y
257>5=FALSE
213>2=FALSE
2810>8=FALSE
2911>9=FALSE
515=5 TRUE
5813>8=FALSE
5913>9=FALSE
189>8=FALSE
1910>9=FALSE
899=9= TRUE

Approach used in the below program is as follows

  • Input an array of integer elements to form an pair

  • Calculate the size of an array pass the data to the function for further processing

  • Create a temporary variable count to store the pairs formed with OR operation having value less than or equals to MAX value amongst the pair

  • Start loop FOR from i to 0 till the size-1 of an array

  • Inside the loop, start another loop FOR from j to i+1 till the size of an array

  • Inside the loop, check IF arr[i] | arr[j] <= max(arr[i], arr[j]) then increment the count by 1

  • Return the count

  • Print the result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//Count pairs with bitwise OR less than Max
int Pair_OR(int arr[], int size){
   int count = 0;
   for (int i = 0; i lt; size - 1; i++){
      for (int j = i + 1; j lt; size; j++){
         if ((arr[i] | arr[j]) lt;= max(arr[i], arr[j])){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 4, 8, 9, 10, 23};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs with bitwise OR less than Max are: "<<Pair_OR(arr, size);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of pairs with bitwise OR less than Max are − 3
raja
Published on 31-Aug-2020 09:21:40
Advertisements