samedi 27 août 2016

third largest and smallest number for pairwise swap of number

This is the code for finding 3rd largest and 3rd smallest number.

t=no of test cases

num=user input number

if num is a single digit number it will print impossible.

if the num is 123 then it should store 123,132,213,231,312,321.

Of these the 3rd from the front is 213 and from back is 231.

The problem of my code is that when i input

123 it gives random number with 112,211,133,311...etc

which i don't want.

I want a 3 digit number containing 1,2 and 3.

if the num is 1234 it should have 4321,2134,3124...Not 1143,2211.

The problem method is solve(int num). In this method i have converted integer num to string num and then stored it in the string treeset which i will again convert it into integer treeset so to find 3rd largest and 3rd smallest number.

iam not sure about primefact method(it gives factorial{length of a number ) whether it has use or not...

public class ThirdSmallestLargest {
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    ThirdSmallestLargest tsl=new ThirdSmallestLargest();
    int t,num;
    t=in.nextInt();
    while(t!=0){
        num=in.nextInt();
        tsl.match(num);
        t--;
    }
}
//---------------------Method for finding zero in a number
private void match(int num) {
    int length=(int) (Math.log10(num)+ 1);
    if(length==1){
        System.out.println("Not possible");
    }
    else{
           String s = String.valueOf(num);
           if (s.indexOf('0')<0){
               solve(num);
           }  
    }
}  
//---------------------method for distinct jumble number
 //NOT DONE CONVERT STRING TREESET TO INTEGER TREESET
private void solve(int num) {
        int length=(int) (Math.log10(num)+ 1);
       TreeSet <String> tsstr=new TreeSet<>();
       Iterator<String> itr=tsstr.iterator();
       //Integer.toString(num);
       char[] chars = Integer.toString(num).toCharArray();
      StringBuilder sb = new StringBuilder(); // doesnt work with 666,7979 types of number
       Random random =  new Random();  
       while (tsstr.size() <fact(num)){
       for (int i = 0; i < length; i++) {                                 
       char c = chars[random.nextInt(chars.length)];
           sb.append(c);

        }           
        String output = sb.toString();
        sb.setLength(0);//set the length of the char

       // String input=sb.toString();
        //System.out.println(output);
       // if(output.contentEquals("1"))
      // tsstr.add(Integer.toString(num));

        tsstr.add(output);   
    }
       System.out.println(tsstr);


}

private int fact(int num) {
    int length=(int) (Math.log10(num)+ 1);
    int i,fact=1;
    for(i=1;i<=length;i++){
       fact=fact*i;
    }
    return fact;
 }
}




Aucun commentaire:

Enregistrer un commentaire