Maximum possible XOR of every element in an array with another array in C++

C++Server Side ProgrammingProgramming

Problem statement

Two arrays A and B consisting of N elements are given. The task is to compute the maximum possible XOR of every element in array A with array B

Example

If input arrays are:
arr1[] = {1, 3, 4, 12}
arr2[] = {5, 9, 5, 7} then maximum possible XOR is:
{8, 10, 13, 1}
Let us take first element of an arr1 and do XOR with all the
elements of arr2 and print the maximum. For example:
(1^5) = 4
(1^9) = 8
(1^5) = 4
(1^7) = 6
From above result 8 the maximum value. Perform same steps for
remaining elements of an array

Algorithm

check every element of array A with every other element of array B and print the maximum xors

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printMaxXor(int *arr1, int *arr2, int n) {
   int maxXor;
   cout << "Maximum possible XOR:\n";
   for (int i = 0; i < n; ++i) {
      maxXor = INT_MIN;
      for (int j = 0; j < n; ++j) {
         int res = arr1[i] ^ arr2[j];
         if (res > maxXor) {
            maxXor = res;
         }
      }
      cout << maxXor << " ";
   }
   cout << endl;
}
int main() {
   int arr1[] = {1, 3, 4, 12};
   int arr2[] = {5, 9, 5, 7};
   int n = sizeof(arr1) / sizeof(arr1[0]);
   printMaxXor(arr1, arr2, n);
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Maximum possible XOR:
8 10 13 11
raja
Published on 21-Jan-2020 11:01:01
Advertisements