XOR Game CodeChef Solution

Problem -XOR Game CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

XOR Game CodeChef Solution in C++17

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
 
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;

typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;

typedef vector<int> vi;
typedef vector<ll> vll;

#define all(v)       v.begin(),v.end()
#define sz(x)        (int)(x).size()
#define alr(v)       v.rbegin(),v.rend()
#define pb           push_back
#define S            second
#define F            first
#define pow2(x)      (1<<(x))
#define sp(x)        cout<<fixed<<setprecision(6)<<x
#define output(x)    cout<<(x?"YES\n":"NO\n")
#define bp(x)        __builtin_popcount(x)
//#define int long long
template<class T> using ordered_set = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
// order_of_key (k) : Number of items strictly smaller than k .
// find_by_order(k) : K-th element in a set (counting from zero).

template<typename T>
void uniq(vector<T> &v) { sort(all(v)); v.resize(unique(all(v)) - v.begin()); }

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

const int N=1e6+1;
const char nl='\n';
const ll mod=1e9+7;
const ll Binf=1e18;
const ll mod1=998244353;

int cnt[N];
void ok(vector<int>b){
    for(int i=0;i<sz(b);i++){
        cnt[b[i]]=0;
    }
}
void solve101(){
    int n;
    cin>>n;
    vector<int>a(n),b(n);
    int ans=0;
    for(int i=0;i<n;i++){
        cin>>a[i];
        ans^=a[i];
    }

    for(int j=0;j<n;j++){
        cin>>b[j];
        ans^=b[j];
        cnt[b[j]]++;
    }
    vector<int>v(n,0);
    for(int i=0;i<n;i++){
        int ned=ans^a[i];
        if(cnt[ned]==0){
            ok(b);
            cout<<-1<<nl;
            return;
        }
        v[i]=ned;
        cnt[ned]--;
    }
    for(int i=0;i<n;i++){
        cout<<v[i]<<" ";
    }
    ok(b);
}
signed main() {

    ios::sync_with_stdio(0);
    cin.tie(0); 
    cout.tie(0);
    
    int t=1;
    cin>>t; 
    for(int i=1;i<=t;i++){
        // cout<<"Case #"<<i<<": ";
        solve101();  
    }
    cerr << "Time : " << 1000 * ((double)clock()) / (double)CLOCKS_PER_SEC << "ms\n";
    return 0;
}
// always check for binary search >.<

// #ifndef ONLINE_JUDGE
//     if (fopen("input.txt", "r"))
//     {
//         freopen("input.txt", "r", stdin);
//         freopen("output.txt", "w", stdout);
//     }
// #endif

XOR Game CodeChef Solution in C++14

#include <bits/stdc++.h>
//for policy based ds //p.order_of_key() -> returns index of value //*p.find_by_order(3) ->value at index
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#include <functional> // for less

using namespace __gnu_pbds; //for policy based ds
using namespace std;

#define int long long
#define pii pair<int, int>
#define vi vector<int>
#define maxHeap priority_queue<int>;
#define minHeap priority_queue<int, vi, greater<int>>
#define mod 1000000007
#define inf 1e18
#define rep(i, s, n) for (int i = s; i < n; i++)
#define sp(ans, pre) fixed << setprecision(pre) << y
#define pb push_back
#define srt(v) sort(v.begin(), v.end())
#define all(v) begin(v), end(v)
#define inputArr(i, arr) \
    for (int &i : arr)   \
        cin >> i;
#define ll long long
#define ull unsigned long long
#define lld long double
#define kickPrint(tt) cout << "Case #" << tt << ": "

typedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> pbds;

time_t Begin;

//////////////////Debug///////////////
#define debug(x)       \
    cout << #x << " "; \
    _print(x);         \
    cout << endl;
void _print(ll t)
{
    cout << t;
}
//void _print(int t) {cout << t;}
void _print(string t) { cout << t; }
void _print(char t) { cout << t; }
void _print(lld t) { cout << t; }
void _print(double t) { cout << t; }
void _print(ull t) { cout << t; }
void display(ll a[], ll n)
{
    for (ll i = 0; i < n; i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;
}

template <class T, class V>
void _print(pair<T, V> p);
template <class T>
void _print(vector<T> v);
template <class T>
void _print(set<T> v);
template <class T, class V>
void _print(map<T, V> v);
template <class T>
void _print(multiset<T> v);
template <class T, class V>
void _print(pair<T, V> p)
{
    cout << "{";
    _print(p.first);
    cout << ",";
    _print(p.second);
    cout << "}";
}
template <class T>
void _print(vector<T> v)
{
    cout << "[ ";
    for (T i : v)
    {
        _print(i);
        cout << " ";
    }
    cout << "]";
}
template <class T>
void _print(set<T> v)
{
    cout << "[ ";
    for (T i : v)
    {
        _print(i);
        cout << " ";
    }
    cout << "]";
}
template <class T>
void _print(multiset<T> v)
{
    cout << "[ ";
    for (T i : v)
    {
        _print(i);
        cout << " ";
    }
    cout << "]";
}
template <class T, class V>
void _print(map<T, V> v)
{
    cout << "[ ";
    for (auto i : v)
    {
        _print(i);
        cout << " ";
    }
    cout << "]";
}
template <typename T, typename U>
inline bool chmax(T &a, U b) { return a < b ? (a = b, true) : false; }
template <typename T, typename U>
inline bool chmin(T &a, U b) { return a > b ? (a = b, true) : false; }

void init()
{
    Begin = clock();
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
}
void timeTaken()
{
#ifndef ONLINE_JUDGE
    double time_taken = double(clock() - Begin) / double(CLOCKS_PER_SEC);
    cout << "Execution Time: " << fixed << setprecision(5) << time_taken << "s\n";
#endif
}

vector<int> computeLps(string s, int M)
{
    int len = 0;
    vector<int> lps(M + 20);

    lps[0] = 0;

    int i = 1;
    while (i < M)
    {
        if (s[i] == s[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            if (len != 0)
            {
                len = lps[len - 1];
            }
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
    // debug(len);
    return lps;
}

int ceiling(int x, int y)
{
    int res = x / y;
    if (x % y)
    {
        if (x >= 0)
            res++;
    }
    return res;
}

vector<vector<int>> makePrefix(vector<vector<int>> &grid)
{
    int n = grid.size(), m = grid[0].size();
    vector<vector<int>> prefix(n + 1, vector<int>(m + 1));

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            prefix[i + 1][j + 1] = grid[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j];
        }
    }

    return prefix;
}

int query(int x1, int y1, int x2, int y2, vector<vector<int>> &prefix)
{
    // cout << x1 << " " << y1 << " " << x2 << " " << y2 << endl;

    // cout << "query: " << prefix[x2 + 1][y2 + 1] << " " << prefix[x2 + 1][y1] << " " << prefix[x1][y2 + 1] << " " << prefix[x1][y2] << endl;
    return prefix[x2 + 1][y2 + 1] - prefix[x2 + 1][y1] - prefix[x1][y2 + 1] + prefix[x1][y1];
}

int toInt(string &s)
{
    int res = 0;
    for (char c : s)
        res = res * 10 + (c - '0');
    return res;
}

bool isValid(int i, int j, int n, int m)
{
    return i >= 0 && i < n && j >= 0 && j < m;
}

int dx[] = {-1, 0, 0, 1};
int dy[] = {0, 1, -1, 0};

// const int MX = 100000;
int32_t main()
{
    init();
    //--------------------

    int t = 1;
    cin >> t;
    for (int tt = 1; tt <= t; tt++)
    {
        int n;
        cin >> n;
        vector<int> arr(n), brr(n);
        inputArr(i, arr);
        inputArr(i, brr);
        int eqXor = 0;
        for (int i : arr)
            eqXor ^= i;
        for (int i : brr)
            eqXor ^= i;
        map<int, int> mp;
        for (int i : brr)
            mp[i]++;
        vector<int> res(n);
        bool ok = true;
        for (int i = 0; i < n; i++)
        {
            int val = eqXor ^ arr[i];
            if (mp[eqXor ^ arr[i]] > 0)
            {
                res[i] = val;
                mp[val]--;
            }
            else
            {
                ok = false;
            }
        }

        if (!ok)
            cout << -1;
        else
        {
            for (int i : res)
                cout << i << " ";
        }
        cout << endl;
    }
    //---------------------------
    timeTaken();
    return 0;
}

XOR Game CodeChef Solution in PYTH 3

import itertools

t = int(input())

for _ in range(t):
    N = int(input())
    
    A = list(map(int, input().split(' ')))
    B = list(map(int, input().split(' ')))
    
    ultimate_sum = 0
    
    for i in range(20):
        mask = 1 << i
        count_a = 0
        count_b = 0
        for a,b in zip(A,B):
            if a & mask > 0:
                count_a += 1
            if b & mask > 0:
                count_b += 1
                
        if count_a == 0 and count_b == 0:
            continue
                
        if count_a != count_b:
            ultimate_sum |= (1 << i)
        
        elif (N - count_a) == count_b:
            print(-1)
            break
    
    perm = [a ^ ultimate_sum for a in A]
    
    if sorted(perm) != sorted(B):
        print(-1)
    else:
        print(' '.join(map(str, perm)))

XOR Game CodeChef Solution in C



#include <stdio.h>

#define gc getchar_unlocked
#define MX 100000

int getn(){
  int n = 0; char c = gc(), f = 1;
  while(c != '-' && (c < '0' || c > '9')) c = gc();
  if(c == '-') f = -1, c = gc();
  while(c >= '0' && c <= '9') n = (n<<3) + (n<<1) + c - '0', c = gc();
  return n * f;
}

void sort(int* a, int n){
  if(n < 2) return;
  int p,t,*l,*r;
  p = a[n>>1], l = a, r = a+n-1;
  while(l <= r){
    if(*l < p){ l++; continue; }
    if(*r > p){ r--; continue; }
    t = *l; *l++ = *r; *r-- = t;
  }
  sort(a, r-a+1), sort(l, a+n-l);
}

int a[MX], b[MX], c[MX];
int main(){
  char f;
  int T,N, i, x;

  T = getn();
  while(T--){
    N = getn();
    for(i = 0; i < N; ++i)
      a[i] = getn();
    for(i = 0; i < N; ++i)
      b[i] = getn();

    for(x = i = 0; i < N; ++i)
      x ^= (a[i] ^ b[i]);
    for(i = 0; i < N; ++i)
      a[i] ^= x, c[i] = a[i];
    sort(a, N);
    sort(b, N);
    for(f = 1, i = 0; i < N; ++i)
      if(a[i] != b[i]){ f = 0; break; }

    if(!f){ printf("-1\n"); continue; }
    for(i = 0; i < N; ++i)
      printf("%d ", c[i]);
    printf("\n");
  }
  return 0;
}

XOR Game CodeChef Solution in JAVA

//package kg.my_algorithms.codechef;




import java.io.*;
import java.util.*;

public class Main {
    private static final long MOD = 1_000_000_007L;
    private static final FastReader fr = new FastReader();
    public static void main(String[] args) throws IOException {
        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();
        int testCases = fr.nextInt();
        for(int testCase=1;testCase<=testCases;testCase++){
            int n = fr.nextInt();
            Map<Integer,Integer> freq = new HashMap<>();
            int[] a = new int[n];
            int[] b = new int[n];
            int x = 0;
            for(int i=0;i<n;i++) {
                a[i] = fr.nextInt();
                x = x^a[i];
            }
            for(int i=0;i<n;i++){
                b[i] = fr.nextInt();
                x = x^b[i];
                freq.put(b[i],freq.getOrDefault(b[i],0)+1);
            }
            int[] s = solve(x,a,freq);
            for(int ss: s) sb.append(ss).append(" ");
            sb.append("\n");
        }
        output.write(sb.toString());
        output.flush();
    }
    private static int[] solve(int x, int[] a, Map<Integer,Integer> freq){
        int n = a.length;
        int[] res = new int[n];
        for(int i=0;i<n;i++){
            int b_cur = a[i]^x;
            if(!freq.containsKey(b_cur)) return new int[]{-1};
            int f = freq.get(b_cur);
            if(f == 0) return new int[]{-1};
            res[i] = b_cur;
            f--;
            freq.put(b_cur,f);
        }
        return res;
    }

}





class FastReader {
    BufferedReader br;
    StringTokenizer st;

    public FastReader()
    {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() { return Integer.parseInt(next()); }

    long nextLong() { return Long.parseLong(next()); }

    double nextDouble()
    {
        return Double.parseDouble(next());
    }

    String nextLine()
    {
        String str = "";
        try {
            if(st.hasMoreTokens()){
                str = st.nextToken("\n");
            }
            else{
                str = br.readLine();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }
}

XOR Game CodeChef Solution in PYPY 3

import functools
def xor(lis):
    return functools.reduce(lambda x,y:x^y,lis)
t=int(input())
for u in range(t):
    n=int(input())
    a=list(map(int,input().split()))
    b=list(map(int,input().split()))
    x=xor(a)^xor(b)
    l=[]
    for i in a:
        l.append(i^x)
    h=sorted(l)
    b.sort()
    if(h==b):
        for i in l:
            print(i,end=' ')
        print()
    else:
        print(-1)

XOR Game CodeChef Solution in PYTH

t = int(raw_input())
for i in range(t):
	N = int(raw_input())
	v = 0
	st = raw_input().split()
	A = []
	for x in st:
		n = int(x)
		A.append(n)
		v = v^n
	# endfor x
	st = raw_input().split()
	B = []
	for x in st:
		n = int(x)
		B.append(n)
		v = v^n
	# endfor x
	C = []
	for n in A:
		w = n^v
		C.append(w)
	# endfor n
	D = list(C)
	D.sort()
	B.sort()
	if B == D:
		st = ''
		for n in C:
			st += str(n) + ' '
		# endfor n
		print st
	else:
		print '-1'
	# endif
# endfor i

XOR Game CodeChef Solution in GO

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var scanner *bufio.Scanner

func next() string {
	if !scanner.Scan() {
		panic("Scan returned false")
	}
	return scanner.Text()
}

func nextInt() int {
	txt := next()
	num, err := strconv.Atoi(txt)
	if err != nil {
		panic("Failed converting " + txt)
	}
	return num
}

func readInts(n int) []int {
	nums := make([]int, n)
	for i := 0; i < n; i++ {
		nums[i] = nextInt()
	}
	return nums
}

func dbgf(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format, args...)
}

func countBits(num int, counts []int) {
	for i := uint8(0); i < 20; i++ {
		if (num>>i)&1 == 1 {
			counts[i]++
		}
	}
}

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	//scanner.Buffer(make([]byte, 100100), 100100)
	wtr := bufio.NewWriter(os.Stdout)
	defer wtr.Flush()
	T := nextInt()
	for caseNum := 1; caseNum <= T; caseNum++ {
		N := nextInt()
		A := readInts(N)
		B := readInts(N)

		var onesA, onesB [20]int
		for i := 0; i < N; i++ {
			countBits(A[i], onesA[:])
			countBits(B[i], onesB[:])
		}

		mask := 0
		for bit := uint8(0); bit < 20; bit++ {
			if onesA[bit] == onesB[bit] {

			} else if onesA[bit] == N-onesB[bit] {
				mask |= (1 << bit)
			} else {
				mask = -1
				break
			}
		}
		if mask == -1 {
			fmt.Fprintln(wtr, -1)
		} else {
			for i, x := range A {
				if i > 0 {
					fmt.Fprint(wtr, " ")
				}
				fmt.Fprint(wtr, x^mask)
			}
			fmt.Fprintln(wtr)
		}
	}
}
XOR Game CodeChef Solution Review:

In our experience, we suggest you solve this XOR Game CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the XOR Game CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this XOR Game CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *