The following program demonstrates how to Create a Code using Five Numbers in Java.
As can be seen, we have five numbers as input. The code is to be computed as follows.
At first, we determine which of these numbers are stable and which are unstable. A number is stable when each of its digits has the same frequency. Otherwise, the number is unstable. So, first, we find the frequency of each digit of all the five numbers. Then, we determine, which of these numbers have the same frequencies for all digits and which have not. After that, we compute the sum of stable numbers and the sum of unstable numbers separately. Then, we subtract the second sum from the first to find the code.
For example, suppose we have these five numbers: 1122, 34, 898, 565, and 12. So, the stable numbers are 1122, 34, and 12. Stable sum = 1122+34+12 = 1168. Unstable sum = 898 + 565 = 1463. Code = 1168 – 1463 = -295.
Another example is, Input Numbers are 2255, 234, 987, 1244, and 2226. Sum of stable numbers = 2255+234+987 = 3476. Sum of unstable numbers = 1244+2226 = 3470. So, the code is 3476-3470 = 6.
import java.util.*;
public class StableUnstable
{
public static void main(String[] args)
{
System.out.println("Code = "+findStable(2255,234,987,1244,2226));
}
public static int findStable(int input1, int input2, int input3, int input4, int input5)
{
int password=0;
int sumStable=0, sumUnstable=0;
System.out.println("Five Numbers: "+input1+" "+input2+" "+input3+" "+input4+" "+input5);
if(isStable(input1)){
sumStable+=input1;
}
else{
sumUnstable+=input1;
}
if(isStable(input2))
sumStable+=input2;
else
sumUnstable+=input2;
if(isStable(input3))
sumStable+=input3;
else
sumUnstable+=input3;
if(isStable(input4))
sumStable+=input4;
else
sumUnstable+=input4;
if(isStable(input5))
sumStable+=input5;
else
sumUnstable+=input5;
password=sumStable-sumUnstable;
return password;
}
public static boolean isStable(int n)
{
String str=Integer.toString(n);
char[] ch=new char[str.length()];
for(int i=0;i<str.length();i++)
{
ch[i]=str.charAt(i);
}
ArrayList<CharFrequencies> list=new ArrayList<CharFrequencies>();
try{
list.add(new CharFrequencies(ch[0], 1));
for(int i=1;i<ch.length;i++)
{
boolean found=false;
char c1=ch[i];
Iterator<CharFrequencies> it =list.iterator();
while (it.hasNext()) {
CharFrequencies cob = it.next();
if (cob.getC() == c1) {
cob.f++;
found=true;
}
}
if(!found)
{
list.add(new CharFrequencies(ch[i], 1));
}
}
}catch(Exception e){ //System.out.println(e.getMessage());
}
boolean sameFreq=true;
CharFrequencies cob1=list.get(0);
int my_f=cob1.getF();
Iterator<CharFrequencies> it2 =list.iterator();
while (it2.hasNext()) {
CharFrequencies cob2 = it2.next();
if(cob2.getF() != my_f)
{
sameFreq=false;
break;
}
}
return sameFreq;
}
}
class CharFrequencies
{
public char c;
public int f;
public CharFrequencies(char c, int f)
{
this.c=c;
this.f=f;
}
public char getC()
{
return this.c;
}
public int getF()
{
return this.f;
}
}
Output