optimization - Sum of Hamming Distances -
I started preparing for an interview and came into the problem:
- The integers An array is given
- Now calculate the distance of all pairs of joints in the array in your binary representation.
Example:
given {1,2,3} or {001010011} (3 bit to simplify Used) result = HD (001010) + HD (001011) + HD (010,011) = 2 + 1 + 1 = 4; With purely dead force solutions, I know that I can use here, here's the personal count of humming distance:
< Pre> int hemming_distance (unsigned x, unsigned y) {int dist; Unsigned wall; Dist = 0; Val = x ^ y; // Calculate the number of XOS / set bits (Wall! = 0) {// is a bit set, so increase the count and clear bit ++; Val & amp; = VAL - 1; } // Return the number of differentiated bits; } What is the best way to solve this problem?
You can consider different bit-positions, this will give you 32 (or some other number) Gives easy problems, where you have to calculate the sum of all pairs of humming holes, except now it is more than 1-bit number.
1-bit number is their XOR.
And now it has become the easiest case of the problem - it's already split up per bit.
Therefore repeat the answer to that question, calculate a bit position, number of 0 and the number of 1, multiply those people to get the contribution of this bit position Yoga for all bit positions. Make it easier than the problem, because the weight of every problem is 1 in this problem.
Comments
Post a Comment