I have the set of matching pairs say p[0]=(0,1),p[1]=(1,2),p[2]=(4,0),p[3]=(0,5),p[4]=(2,4),p[5]=(3,3),p[6]=(5,1),p[7]=(1,7),p[8]=(2,6) now,I want to print those pairs whose sum is same but the difference between the elements of each pair is minimum. i.e. say p[4],p[5],p[6] have the same sum 6. the difference of elements in p[4] is 2 ,in p[5] is 0 & in p[6] is 4. so we will choose p[5]. the result should print p[1],p[2],p[3],p[5],p[8]. I am trying but not get the results so please help me.
I don't quite get why p[1],p[2],p[3],p[5],p[8] should be the result. I'm giving you the algorithm to calculate sum and difference for each pair, you'll have to handle the rest. Code: #include <stdio.h> #include <stdlib.h> int main() { const char *p[9]; int i, v1, v2, sum[9], difference[9]; p[0] = "(0,1)"; p[1] = "(1,2)"; p[2] = "(4,0)"; p[3] = "(0,5)"; p[4] = "(2,4)"; p[5] = "(3,3)"; p[6] = "(5,1)"; p[7] = "(1,7)"; p[8] = "(2,6)"; for (i = 0; i < 9; ++i) { sscanf(p[i], "(%d,%d)", &v1, &v2); sum[i] = v1 + v2; difference[i] = abs(v1 - v2); } return 0; }
sir,I understand your algo. But I already calculated the sum . I just want to find out those pairs which have equal sum but the difference between the element should be minimum. Like,from the the above example , p[0],p[1],p[2],p[3] dont have the same sum. So this will be printed. But p[4],p[5],p[6] have the same sum so we have to calculate their differences between the elements. Its find that p[5] has the minimum difference i.e. 0 so,we select p[5] . In the same way p[7] & p[8] have the same sum but p[8] has the minimum sum so we have to select p[8]. so the final matching pairs should be, p[0],p[1],p[2],p[3],p[5],p[8].
my code is below, #include<stdio.h> #include<conio.h> #include<string.h> #include<time.h> #include<math.h> #include <stdlib.h> int main() { int b[11]={0,1,4,1,2,2,3,3,4,4,5}; int c[11]={1,6,3,7,4,6,3,8,0,7,1}; int y[11],k=0,p[11],q[11]; for(int i=0;i<11;i++) { for(int j=i+1;j<11;j++) { if((b+c)==(b[j]+c[j])) { y[k]=abs(b-c); y[k+1]=abs(b[j]-c[j]); if(y[k]>y[k+1]) { p=b[j+1]; q=c[j+1]; } else { p=b[j]; q=c[j]; } } else { p=b; q=c; } } printf("%d%d\n",p,q); } getch(); return 0; }