vibe mathematics

XOR | Exclusive OR is bitwise operator that returns 1 if the two bits are different and 0 if they are the same.

The XOR operator is represented by the symbol ^. It takes two operands and returns 1 if the operands are different and 0 if they are the same.

here is the truth table for XOR

a b a ^ b
0 0 0
0 1 1
1 0 1
1 1 0

case i

    1010 
   ^
    1100
  = 0110

case ii

Let’s say we have two numbers, A and B, and we want to know if they are equal or not. We can do this by using the XOR operator.

A ^ B = 10 ^ 11 = 10 ^ 1 = 10 ^ 0 = 10

In this case, the result is 10, which means that A is not equal to B.

a ^ b = 11 ^ 11 = 00 

Here, the result is 0, which means that A is equal to B.

case iii

commutavity of xor, getting to the level whereby depending on the order of the operands, the result is the same. i.e A ^ B = B ^ A

case iv

swapping 2 values in a function, here

func swap(a, b int) (int, int) {
	a ^= b
	b ^= a
	a ^= b

	return a, b
}

func main() {
	a := 3
	b := 5
	a, b = swap(a, b)
	println(a, b)
}

so here is the code right

a = 0011 = 3
b = 0101 = 5

a = a xor b = 0110 = 6
a = 0110 = 6
b = 0101 = 5

b = b xor a = 0011 = 3
a = 0110 = 6
b = 0011 = 3

a = a xor b = 0101 = 5

so like that a = 5 and b = 3

case v

finding a missing number in a sequence, here

func findMissing(arr []int) int {
  n := len(arr) + 1
  res := 0

  //XOR all the numbers from 1 to n
	for i := 1; i <= n; i++ {
    res ^= i
	}

  //XOR the missing number
  for i := 0; i < len(arr); i++ {
    res ^= arr[i]
  }

  return res
}

func main() {
  arr := []int{1, 2, 3, 4, 5, 7, 8, 9, 10}
  println(findMissing(arr))
}

straight forward, we XOR all the numbers from 1 to n, then we XOR the missing number, and that’s it.

we xor all the numbers from 1 to n, 
we XOR with the number in the array, 
so we get the missing number

case vi

finding two missing or duplicate number in a sequence, - more complex part of it that will be shown soon