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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With