Check if a number from every row can be selected such that xor of the numbers is greater than zero in C++


Suppose we have one 2D array of size N x M. The task is to check if we can select a number from every row, in such a way that the XOR of those elements is non-zero or greater than 0. Suppose one matrix is like this −

777
10107

If we perform XOR, the answer will be non-zero, as the except last elements of two rows are 7 and 10

To solve this problem, the solution will be very easy. Initially check if XOR of the elements of the first column of each row is 0 or not. If it is non-zero then it is possible. otherwise, check if any of the rows have two or more distinct elements or not, if yes then also it is possible. If both of the above conditions are not satisfied, then it is not possible.

Example

 Live Demo

#include<iostream>
using namespace std;
#define N 2
#define M 3
bool isXORnonZero(int matrix[N][M]) {
   int xor_value = 0;
   for (int i = 0; i < N; i++) {
      xor_value ^= matrix[i][0];
   }
   if (xor_value != 0)
      return true;
   for (int i = 0; i < N; i++) {
      for (int j = 1; j < M; j++) {
         if (matrix[i][j] != matrix[i][0])
         return true;
      }
   }
   return false;
}
int main() {
   int mat[N][M] = {
      { 7, 7, 7 },
      { 10, 10, 7 }
   };
   if (isXORnonZero(mat))
      cout << "XOR has non-zero value";
   else
      cout << "XOR has zero value";
}

Output

XOR has non-zero value

Updated on: 22-Oct-2019

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements