Breaking

Friday 9 June 2017

Sort numbers based on weight - Zoho

         Sort numbers based on weight - Zoho

                                     Image result for zoho logo

Given a set of N numbers and the rules provided below to calculate their weights, the program must sort the numbers based on their weight and print the numbers in ascending order.
Rules to calculate weight:  
- 5 if a perfect square
- 4 if multiple of 4 and divisible by 6
 - 3 if even number

Input Format:

The first line contains the value of N.
The next N lines contain the value of N numbers.

Boundary Conditions:
The length of the array of numbers will be from 3 to 200.
1 <= N <= 20

Output Format:
N lines containing the sorted numbers based on their weight.

Example Input/Output 1:

Input:
5
10
36
54
49
12
Output:
36
12
49
54
10
Explanation:
10's weight = 3 for just being an even number.
36's weight = 5+4+3 = 12 (as it is a perfect square of 6, multiple of 4 and divisible by 6 and also it is an even number)
54's weight = 3 for just being an even number
49's weight = 5 (as it is a perfect square of 7)
12's weight = 4+3 = 7 (multiple of 4 and divisible by 6 and also it is an even number)
In this 10 and 54 have same weight which is 3. Between them 54 is larger. So it is printed first.

Example Input/Output 2:
Input:
4
89
81
72
99
Output:
72
81
99
89
Explanation:
89's weight = 081's weight = 5 (for just being a perfect square)
72's weight = 4+3 = 7 (multiple of 4 and divisible by 6 and also it is an even number)
99's weight = 0As 99 is greater than 89, 99 is printed first.

Code:

import java.util.*;

public class Hello {


    public static void main(String[] args) {

     Scanner sc=new Scanner(System.in);

         int n=sc.nextInt();

        int[] arr=new int[n];

        int[] wt=new int[n];

        int[] ip=new int[n];

        int i,j=0;

        for(i=0;i<n;i++)

             ip[i]=sc.nextInt();

        Arrays.sort(ip);

        for(i=n-1;i>=0;i--)

             arr[j++]=ip[i];

        for(i=0;i<n;i++)

         {

             wt[i]=0;

             int sq=(int)Math.sqrt(arr[i]);

             if((sq*sq)==arr[i])

                 wt[i]+=5;

            if((arr[i]%6==0)&&(arr[i]%4==0))

                 wt[i]+=4;

             if(arr[i]%2==0)

                 wt[i]+=3;

         } 

         int t,temp;

            for(i=0;i<n-1;i++)

                {

                    for(j=0;j<n-i-1;j++)

                        {

                            if(wt[j]<wt[j+1])

                            {

                               t=wt[j];

                               wt[j]=wt[j+1];

                               wt[j+1]=t;

                               temp=arr[j];

                               arr[j]=arr[j+1];

                                arr[j+1]=temp;

                            }

                        }
            for(i=0;i<n;i++)
                System.out.print(arr[i]+" ");
}
}

No comments:

Post a Comment

Like