Saturday, 9 December 2017

Array sorting based weight of elements

Problem:  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 weight and print it as follows

<10,its_weight>,<36,its weight><89,its weight>

Should display the numbers based on increasing order.

Program:

#include<iostream>
#include<math.h>
using namespace std;
bool even(int x);
bool divisible(int x);
bool perfectsqr(int x);
int main()
{
    int arr[5]={10,36,54,89,12};
    int sum[5],i,temp;
    for(i=0;i<5;i++)
    {
         sum[i]=0;
         if(perfectsqr(arr[i]))
                sum[i]=sum[i]+5;
         if(divisible(arr[i]))
                sum[i]=sum[i]+4;
         if(even(arr[i]))
                sum[i]=sum[i]+3;
       
    }
    for(i=0;i<4;i++)
    {
        for(int j=i;j<5;j++)
        {
            if(sum[i]<sum[j])
            {
                 temp=sum[i];
                 sum[i]=sum[j];
                 sum[j]=temp;
                 temp=arr[i];
                 arr[i]=arr[j];
                 arr[j]=temp;
            }
        }
    }
    for(i=0;i<5;i++)
    {
        cout<<"<"<<arr[i]<<","<<sum[i]<<">";
        if(i!=4)
        cout<<",";
    }
    return 0;
}
bool even(int x)
{
    if(x%2==0)
        return 1;
    else
        return 0;
}
bool divisible(int x)
{
    if(x%4==0 && x%6==0)
        return 1;
    else
        return 0;
}
bool perfectsqr(int x)
{
   int ires;
    float fres=sqrt(x);
    ires=fres;
    if(ires==fres)
        return 1;
    else
        return 0;
}
Sample output:



No comments:

Post a Comment