Here's a cool solution in C (++)
int a[3], b[3]; int c[4]; int s=0, t=0, k; int i; for (i=0;i<3;i++) { k = a[i]-b[i]; s += k; t += k*(a[i]+b[i]); } t /= s; int x = (s + t) / 2; int y = (t - s) / 2; c[0] = x; c[3] = y; c[1] = (a[0] == x ? a[1] : a[0]); c[2] = (a[2] == x ? a[1] : a[2]);
Example: a = {1, 3, 5}, b = {3, 5, 2}
s = (1-3)+(3-5)+(5-2) = -2-2+3 = -1 t = (1-3)*(1+3)+(3-5)*(3+5)+(5-2)*(5+2) = -8-16+21 = -3 t / s = 3 x = (-1 + 3) / 2 = 1 y = (3 - (-1)) / 2 = 2 c[0] = 1 c[3] = 2 c[1] = 3 c[2] = 5
therefore c gets the value {1,3,5,2} as desired!
For fun, the following version is here:
/* Declarations */ int a[3], b[3], c[4]; int s = 0, t = 0, k, i; /* Actual algorithm */ for (i = 0; i < 3; i++) { s += (k = a[i]-b[i]); t += k * (a[i]+b[i]); } t /= s; c[0] = (s + t) >> 1; c[3] = (t - s) >> 1; c[1] = (a[0] == x ? a[1] : a[0]); c[2] = (a[2] == x ? a[1] : a[2]);
Note that it is cold enough if the problem is generalized, so that n-1 elements are separated, and in both arrays there is one unique element, this is the O (n) algorithm, while many intersection and / or union algorithms are based on O (n log n) :)
Antti huima
source share