Monday, 5 June 2017

To find sum of weights in a given array

  Given a set of numbers like <10, 36, 54,89,12> we want to find sum of weights based on the following conditions
    1. 5 if a perfect square
    2. 4 if multiple of 4 and divisible by 6
    3. 3 if even number

And sort the numbers based on the above condition and print it as follows
<10,its_weight>,<12,its weight><36,its weight><54,its weight>
Should display the numbers based on increasing order.


#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int n,i,j,t1,t2;
scanf("%d",&n);
int *a=(int *)malloc(n*sizeof(int)); //create dynamic array for size n
int *b=(int *)calloc(n,sizeof(int)); // set all weightage to zero
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
//to check and find weightage
for(i=0;i<n;i++)
{
if(sqrt(a[i])*sqrt(a[i])==a[i])
{
b[i]+=5;
}
if(a[i]%4==0&&a[i]%6==0)
{
b[i]+=4;
}
if(a[i]%2==0)
{
b[i]+=2;
}
}
// to sort number in ascending
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t1=a[i];t2=b[i];
a[i]=a[j];b[i]=b[j];
a[j]=t1;b[j]=t2;
}
}
}
//printing the weightage
for(i=0;i<n;i++)
{
if(b[i]!=0)
printf("<%d,%d> ",a[i],b[i]);
}
return 0;
}

OUTPUT : 


   

No comments:

Post a Comment