Friday 21 July 2017

Sort the numbers based on the weight in decreasing order

Number Weight
Given a set of numbers like <10, 36, 54,89,12> write a program 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


Print the output as follows.
(10,its_weight)(36,its weight)(89,its weight)

Note: Sort the numbers based on the weight in decreasing order. If 2 weights are same, display the numbers based on increasing order.

Sample Input:
5
10 36 54 89 12
Sample Output:
(36,12)(12,7)(10,3)(54,3)(89,0)


                                           C-Solution 
#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));
int *b=(int *)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

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]+=3;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(b[i]<b[j])
{
t1=a[i];t2=b[i];
a[i]=a[j];b[i]=b[j];
a[j]=t1;b[j]=t2;
}
else if(b[i]==b[j])
{
t1=a[i];a[i]=a[j];a[j]=t1;
}
}
}
for(i=n-1;i>=0;i--)
{
printf("(%d,%d)",a[i],b[i]);
}
return 0;
}

No comments:

Post a Comment