Paparazzi Paparazzi - 1 year ago 83
C# Question

How to exit recursion

With my code below the problem is the found is false.

It finds the password and gets to the

return true;
but it keeps on running.

How can back out of the recursion and stop at
return true;

string password = "password";
char[] chars = new char[] { 'a', 'b', 'c', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's' , 't', 'u', 'v', 'w', 'x', 'y', 'z' };

bool found = MatchPassword(chars, 8, string.Empty, password);

static int counter = 0;
public static bool MatchPassword(char[] chars, int maxLen, string baseGuess, string actualPassword)
int curLen = baseGuess.Length;
if (curLen == maxLen)
return false;
for (int i = 0; i < chars.Length; i++)
string nextGuess = baseGuess + chars[i];
if (counter % 1000000 == 0 || curLen == 0 || nextGuess.StartsWith("passwo")) //
if (nextGuess == actualPassword)
return true;
MatchPassword(chars, maxLen, nextGuess, actualPassword);
return false;

Answer Source

It should be:

 else if (Match...) return true;

Or even:

    if (nextGuess == actualPassword || Match...)
        return true;

Because you want to continue iterations when current fails and stop if something found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download