Number Weight
Given a set of numbers like <10, 36, 54,89,12> write a program to find the sum of weights based on the following conditions1. 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)
public class NewClass8 {
void print(int ar[],int br[])
{
for(int i=0;i<ar.length;i++)
{
System.out.println(ar[i]+" "+br[i]);
}
}
void sort(int ar[],int br[])
{
for(int i=0;i<ar.length;i++)
{
for(int j=i+1;j<br.length;j++)
{
if(br[i]<br[j])
{
br[i]=br[i]+br[j];
br[j]=br[i]-br[j];
br[i]=br[i]-br[j];
ar[i]=ar[i]+ar[j];
ar[j]=ar[i]-ar[j];
ar[i]=ar[i]-ar[j];
}
}
}
}
int[] weight(int ar[])
{
int br[]=new int[ar.length],sum=0;
for(int i=0;i<ar.length;i++)
{ sum=0;
if(ar[i]%4==0 && ar[i]%6==0)
{
sum+=4;
}
if(ar[i]%2==0)
{
sum+=3;
}
if((int)Math.sqrt(ar[i])*(int)Math.sqrt(ar[i])==ar[i])
{
sum+=5;
}
br[i]=sum;
}return br;
}
public static void main(String args[])
{
int ar[]={10,36,54,89,12};
int br[]=new int[ar.length];
NewClass8 ob=new NewClass8();
br=ob.weight(ar);
ob.sort(ar,br);
ob.print(ar, br);
}
}
No comments:
Post a Comment