I am a student and I’ve been given an assignment to crack a password(n characters long, n is given in the method, all a-z). the tricky part:
-
no loops at all- all recursion
-
the only way to check if your answer is true is comparing with the entire password. cant check letter-letter
-
if you want to use method from the String class, you can only use the following ones: charAt, equals, length, substring.
-
cant use any other classes.
-
cant call the recursive method 26 times with each letter, in 26 different lines. when I asked my professor about this he just said “come on dude”.
I already did an algorithm that covers all options for an n-length password, like so(for n=3 for example):
aaa, baa, caa … zaa -> aaa. bba, cba, … , zba, and so on. I am not sure it fully works now that I think about it, so if you have any notes on that it would be nice too. here it is: (note that I don’t have the code for the Password class, it’s a black box. the only thing I can use from it is the .isPassword() method.
public static String findPassword (Password p, int length){
return findPassword(p, length, "");
}
private static String findPassword(Password p,int length, String str){
if(str.length()<length){
str+='a';
findPassword(p,length, str);
}
if(p.isPassword(str)){
return str;
}
return findPassword(p,length,changeString(str,0));
}
private static String changeString(String str, int index){
if(str.charAt(index) == 'z'){
str = str.substring(0, index) + 'a' + str.substring(index + 1);
return changeString(str,index + 1);
}
return str.substring(0, index) + (char)(str.charAt(index) + 1) + str.substring(index + 1);
}
but for the main problem: it works perfectly in 2 letter passwords and sometimes 3. the problem is that in java you can only do 2000 recursive calls until you get hit with a stack overflow, and of course for 4,5 letter passwords it will take 26^4,5 >>> 2000. the question is, how can I bypass this restriction? thought about sending it every x calls to another method, which calls back to the original method, but I couldn’t figure out quite how, or if it would really worked even if I managed to do that. maybe one of y’all knows more about it? thanks in advance 🙂
ori ben dror is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.