Wednesday, June 8, 2016

C program to select elements from three given array and make sum of zero

Problem Statement: you're given three arrays and you have to pick one element from each array to make sum of zero
Example
 int a[]={1,7,5,9};
 int b[]={-2,-1,1,2};
 int c[]={-8,-7,1,-8};
taking 1 from a,-2 from b and 1 from c is making a combination with sum as zero
1 + -2 + 1 = 0

now ignoring these values, and repeating the process
taking 7 from first array, taking -1 from b isn't suiting with any element of c, taking 1 from b and -8 from c making combination with sum as zero
7 + 1 + -8 = 0

repeat this procedure

#include<stdio.h>
void main()
{
 int a[]={1,7,5,9};
 int b[]={-2,-1,1,2};
 int c[]={-8,-7,1,-8};
 int i,j,k;
 int occupy[100];
 int count=0, flag=0,temp;
 for(i=0;i<4;i++)
  {
   for(j=0;j<4;j++)
    {
     for(k=0;k<4;k++)
      {
       if((a[i]+b[j]+c[k])==0)
{
flag=0;
temp=count;
while(temp>0)
{
 if((i==occupy[temp*3-3])||(j==occupy[3*temp-2])||(k==occupy[3*temp-1]))
  {
   flag=1;
   break;
  }
  temp--;
 }
 if(flag==0)
  {
   printf("%d %d %d \n",a[i],b[j],c[k]);
   count++;
   occupy[3*count-3]=i;
   occupy[3*count-2]=j;
   occupy[3*count-1]=k;
  }
}
      }
    }
  }
}

output
1 -2 1
7 1 -8
5 2 -7
9 -1 -8

No comments:

Post a Comment