Find a number which give minimum sum when XOR with every number of array of integer in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array A, we have to find a number X such that (A[0] XOR X) + (A[1] XOR X) + … + A[n – 1] XOR X is as minimum as possible.

So, if the input is like [3, 4, 5, 6, 7], then the output will be X = 7 , Sum = 10

To solve this, we will follow these steps −

  • Define a function search_res() . This will take arr, n
  • element := arr[0]
  • for i in range 0 to size of arr, do
    • if arr[i] > element, then
      • element := arr[i]
  • p := integer of (log of element base 2) + 1
  • X := 0
  • for i in range 0 to p, do
    • cnt := 0
    • for j in range 0 to n, do
      • if arr[j] AND (2^i) is non-zero, then
        • cnt := cnt + 1
    • if cnt > integer part of (n / 2) is non-zero, then
      • X := X + (2^i)
  • sum := 0
  • for i in range 0 to n, do
    • sum := sum +(X XOR arr[i])
  • return X and sum

Example

Let us see the following implementation to get better understanding −

from math import log2
def search_res(arr, n):
   element = arr[0]
   for i in range(len(arr)):
      if(arr[i] > element):
         element = arr[i]
   p = int(log2(element)) + 1
   X = 0
   for i in range(p):
      cnt = 0
      for j in range(n):
         if (arr[j] & (1 << i)):
            cnt += 1
      if (cnt > int(n / 2)):
         X += 1 << i
   sum = 0
   for i in range(n):
      sum += (X ^ arr[i])
   print("X =", X, ", Sum =", sum)
arr = [3, 4, 5, 6, 7]
n = len(arr)
search_res(arr, n)

Input

[3, 4, 5, 6, 7]

Output

X = 7 , Sum = 10
raja
Updated on 28-Aug-2020 08:12:07

Advertisements