Paparazzi Paparazzi - 16 days ago 6
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);
Debug.WriteLine(found);
}

static int counter = 0;
public static bool MatchPassword(char[] chars, int maxLen, string baseGuess, string actualPassword)
{
counter++;
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")) //
Debug.WriteLine(nextGuess);
if (nextGuess == actualPassword)
return true;
else
MatchPassword(chars, maxLen, nextGuess, actualPassword);
}
return false;
}

Answer

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.