//Program : Given 3 arrays, find the triplet (containing one element from
//each array) with the minimum distance. The distance of a triplet (a,b,c)
//is defined as max(|a-b|, |b-c|, |c-a|)
#include<stdio.h>
int main()
{
int n1, n2, n3, i, j, k, max, triplet_dist, trip_dist;
int a1[10], a2[10], a3[10], triplet[3];
// Input the 3 arrays
printf("Enter the sizes of the 3 matrices\n");
scanf("%d %d %d", &n1, &n2, &n3);
printf("Enter the elements of the first array\n");
for(i = 0; i < n1; i++)
scanf("%d", &a1[i]);
printf("Enter the elements of the second array\n");
for(i = 0; i < n2; i++)
scanf("%d", &a2[i]);
printf("Enter the elements of the third array\n");
for(i = 0; i < n3; i++)
scanf("%d", &a3[i]);
// Initialization of min distance
triplet_dist = 9999;
// Compute min distance of triplet
for(i = 0; i < n1; i++)
for(j = 0; j < n2; j++)
for(k = 0; k < n3; k++)
{
// find out the distance of the triplet
max = abs(a1[i] - a2[j]);
if(abs(a2[j] - a3[k]) > max)
max = abs(a2[j] - a3[k]);
if(abs(a1[i] - a3[k]) > max)
max = abs(a1[i] - a3[k]);
// If the distance found is less than the already found min
// distance, update triplet array and triplet distance
if(max < triplet_dist)
{
triplet_dist = max;
}
}
// Print the min distance triplets
printf("The minimum distance is %d\n", triplet_dist);
printf("The min distance triplets are:\n");
trip_dist = 9999;
for(i = 0; i < n1; i++)
for(j = 0; j < n2; j++)
for(k = 0; k < n3; k++)
{
// findout the distance of the triplet
max = abs(a1[i] - a2[j]);
if(abs(a2[j] - a3[k]) > max)
max = abs(a2[j] - a3[k]);
if(abs(a1[i] - a3[k]) > max)
max = abs(a1[i] - a3[k]);
if(max == triplet_dist)
{
printf("(");
printf("%d %d %d", a1[i], a2[j], a3[k]);
printf(")");
printf("\n");
}
}
return 0;
}
Written by Munia Balayil
Wednesday, September 12, 2012
Minimum Distance Triplet in C
Subscribe to:
Posts (Atom)