Find the original Array using XOR values of all adjacent elements | C ++ implementation to find the Array from the XOR array of the adjacent elements of array ; XOR of all elements from 1 to N ; Function to find the Array from the XOR Array ; Take a vector to store the permutation ; XOR of N natural numbers ; Loop to find the XOR of adjacent elements of the XOR Array ; Loop to find the other elements of the permutation ; Finding the next and next elements ; Driver Code ; Required Permutation
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xor_all_elements ( int n ) { switch ( n & 3 ) { case 0 : return n ; case 1 : return 1 ; case 2 : return n + 1 ; case 3 : return 0 ; } } vector < int > findArray ( int xorr [ ] , int n ) { vector < int > arr ; int xor_all = xor_all_elements ( n ) ; int xor_adjacent = 0 ; for ( int i = 0 ; i < n - 1 ; i += 2 ) { xor_adjacent = xor_adjacent ^ xorr [ i ] ; } int last_element = xor_all ^ xor_adjacent ; arr . push_back ( last_element ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { last_element = xorr [ i ] ^ last_element ; arr . push_back ( last_element ) ; } return arr ; } int main ( ) { vector < int > arr ; int xorr [ ] = { 7 , 5 , 3 , 7 } ; int n = 5 ; arr = findArray ( xorr , n ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { cout << arr [ i ] << " ▁ " ; } }