javascriptarraysbitwise-xor

Why do Bitwise XOR ( ^ ) given example results differ? What is the logic? JS


A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

For example, in array A such that:

A[0] = 9  A[1] = 3  A[2] = 9
A[3] = 3  A[4] = 9  A[5] = 7
A[6] = 9

the elements at indexes 0 and 2 have value 9, the elements at indexes 1 and 3 have value 3, the elements at indexes 4 and 6 have value 9, the element at index 5 has value 7 and is unpaired. Write a function:

function solution(A);

that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.

For example, given array A such that:

 A[0] = 9  A[1] = 3  A[2] = 9
 A[3] = 3  A[4] = 9  A[5] = 7
 A[6] = 9

the function should return 7, as explained in the example above.

function different(a) {
  let result = 0;

    for (let element of a) {
        result ^= element
    }

  return result;
}

const arr = [9, 3, 9, 3, 9, 7, 9];

I found this solution which works pretty well with the required condition. I didn't understand use of Bitwise XOR ( ^ )

I also tested with different arrays;

 arr = [9, 3, 9, 3, 9, 7, 9];  //returns 7 
 arr = [9];                    //returns 9
 arr = [9, 3];                 //returns 10
 arr = [9, 3, 9, 3];           //returns 0
 arr = [9, 3, 9, 9 ];          //returns 10
 arr = [9, 3, 9, 2 ];          //returns 2

Could anyone explain to me how it works? What is the logic behind it? Why does it only work perfectly with the required condition?


Solution

  • This code works because when you XOR a number with 0, you get the number, and when you XOR a number with itself, you get 0. For your specific conditions of an array with only one unpaired number ([9, 3, 9, 3, 9, 7, 9]), you can unroll your loop to look like

    result = 0 ^ 9 ^ 3 ^ 9 ^ 3 ^ 9 ^ 7 ^ 9 
    

    and since

    a ^ b = b ^ a 
    

    this can be rewritten as

    result = 0 ^ 9 ^ 9 ^ 3 ^ 3 ^ 7 ^ 9 ^ 9
           = 0 ^ 0 ^ 0 ^ 7 ^ 0
           = 7
    

    The reason this doesn't work when there is more than one unmatched value is that the result you end up with is the XOR of all the unmatched values. For example, for [9, 3, 9, 9] you get

    result = 9 ^ 3 ^ 9 ^ 9
           = 9 ^ 3 ^ 0
           = 10