Maximum XOR value in matrix in C++

C++Server Side ProgrammingProgramming

<p style="">In this problem, we are given a matrix of size n X n. Our task is to create a program that will calculate the maximum XOR value of a complete row or a complete column.</p><p>Let&rsquo;s take an example to understand the problem,</p><p><strong>Input</strong> &minus;</p><pre class="result notranslate">N = 3 mat[N][N] = {{4, 9, 1} {2, 8, 3} {10, 12, 11}}</pre><p><strong>Output</strong> &minus;</p><pre class="result notranslate">13</pre><p><strong>Explanation</strong> &minus;</p><pre class="result notranslate">Row1: 4^9^1 = 12 Row2: 2^8^3 = 9 Row3: 10^12^11 = 13 Col1: 4^2^10 = 12 Col2: 9^8^12 = 13 Col3: 1^3^11 = 9</pre><p>Here, we have calculated the XOR of all rows and columns and then the maximum of them is printed.</p><p>To solve this problem, we will calculate the XOR of all rows and columns of the matrix and find the maximum of them.</p><p>One way of finding the XOR of rows and columns is iterating the matrix 2 times, one for columns and other for rows.</p><p>But we can do the same using one iteration over the square matrix. And one for row-wise and other for column-wise.</p><p>This can be done using the same iteration by using matrix[i][j] for traversing row-wise matrix[j][i] for traversing column-wise</p><h2>Example</h2><p>Program to show illustrate our solution,</p><p><a class="demo" href="http://tpcg.io/WRcp2dQH" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">#include&lt;iostream&gt; using namespace std; const int MAX = 1000; int maxRCXOR(int mat[][MAX], int N){ &nbsp; &nbsp;int rowXOR, colXOR; &nbsp; &nbsp;int maxXOR = 0; &nbsp; &nbsp;for (int i = 0 ; i &lt; N ; i++){ &nbsp; &nbsp; &nbsp; rowXOR = 0, colXOR = 0; &nbsp; &nbsp; &nbsp; for (int j = 0 ; j &lt; N ; j++){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;rowXOR = rowXOR^mat[i][j]; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;colXOR = colXOR^mat[j][i]; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; if (maxXOR &lt; max(rowXOR, colXOR)) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;maxXOR = max(rowXOR, colXOR); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; return maxXOR; } int main() { &nbsp; &nbsp;int N = 3; &nbsp; &nbsp;int matrix[][MAX]= { &nbsp; &nbsp; &nbsp; {4, 9, 1}, &nbsp; &nbsp; &nbsp; {2, 8, 3}, &nbsp; &nbsp; &nbsp; {10, 12, 11} &nbsp; &nbsp;}; &nbsp; &nbsp;cout&lt;&lt;&quot;Maximum XOR of all row XOR and Column XOR is &quot;&lt;&lt;maxRCXOR(matrix,N); &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><pre class="result notranslate">Maximum XOR of all row XOR and Column XOR is 13</pre>
raja
Updated on 03-Jun-2020 07:32:35

Advertisements