Friday, February 25, 2011

Given 3 sorted arrays Let x be an element of A, y of B, z of C.the distance b/w x,y,z =max(|x-y|,|y-z|,|z-x|) Find Touple With Minimum Distance

Given 3 sorted arrays (in ascending order). Let the arrays be A(of n1 length), B(of n2 length), C(of n3 length). Let x be an element of A, y of B, z of C. The distance between x, y and z is defined as the max(|x-y|,|y-z|,|z-x|). Find the tuple with the minimum distance?


#include
#include

#define min2(a,b) (a) < (b) ? (a) : (b)
#define min3(a,b,c) (a) < (b) ? min2(a,c) : min2(b,c)
#define max2(a,b) (a) > (b) ? (a) : (b)
#define max3(a,b,c) (a) > (b) ? max2(a,c) : max2(b,c)


typedef struct
{
int x, y, z;
}Tuple;


Tuple mindist(int a[], int b[], int c[], int m, int n, int l)
{
int i = 0;
int j = 0;
int k = 0;

int distance = INT_MAX;
Tuple out = {-1,-1,-1};


while(i < m && j < n && k < l)
{
//Find max (abs(a[i]-b[j]), abs(b[j]-c[k]), abs(a[i]-c[k])
//Advance minimum of a[i], b[j] and c[l]

int x = abs(a[i]-b[j]);
int y = abs(b[j]-c[k]);
int z = abs(a[i]-c[k]);

int d = max3(x,y,z);
if(d < distance)
{
distance = d;
out.x = i; out.y = j, out.z = k;
}

int min = min3(a[i], b[j], c[k]);

if(min == a[i])
i++;
else if(min == b[j])
j++;
else if(min == c[k])
k++;

}
return out;

}


int main()
{
int m=3, n=4, l=5;


int a[]={1,2,3};
int b[]={5,6,7,8};;
int c[]={10,11,12,13,14};

int i;

Tuple r = mindist(a,b,c,m,n,l);

printf("(%d,%d,%d)\n", r.x,r.y,r.z);
}

No comments :