Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

5th string needed from combination

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.

like image 215
Fawkes Avatar asked Oct 18 '22 11:10

Fawkes


1 Answers

You don't change n after running the check and printing a result in your recursion. That's why you print everything after adbc.

If you use this code when checking:

if (n == times) {
    System.out.println(prefix);
    n = -1;
} else {
    if (n > -1)
        n++;
}

then you only get n == times to be true once, and that's when the prefix is adbc.

Example test for the solution:

output

If you want to stop a method that has no return value (has void in its return type in the method signature), then calling return; will exit the method... But it isn't needed here.

like image 126
ItamarG3 Avatar answered Oct 21 '22 04:10

ItamarG3