5th string needed from combination

Viewed 83

Suppose there is a string s=abcd

I want the 5th string consisting of a,b,c,d, which is adbc. But I also get all the answers beyond it which I don't need.

So how can I stop this method after its 5th execution?

import java.util.Arrays;
import java.util.Scanner;

class Test{
   long times;
   int n=1;

   public static void main(String[] args) {
        Test tm=new Test();
        Scanner in=new Scanner(System.in);
        int t=Integer.parseInt(in.nextLine());

        while(t!=0){
            String s=in.nextLine();
            char ch[]=s.toCharArray();          
            Arrays.sort(ch);
            String sort=String.valueOf(ch);            
            String ans;
            long n=Long.parseLong(in.nextLine());
            tm.times=n;
            tm.permu("",sort);
            t--;           
        }
    }

    private void permu(String prefix,String str) {
        int len=str.length();          

        if(len==0){
            if(n==times){
                System.out.println(prefix);
            }
            else{
                n++;
            }
        }
        else{
            for(int i=0;i<len;i++){
                permu(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, len));
            }
        }      
    }
}

Secondly is there any site where I can read about permutation, combination and probability for calculating and finding the permutation, combination and probability... For coding thing not for mathematical thing..i.e I know how to solve mathematically but I can't code it.. Unable to write logic for it.

1 Answers
Related