与我的代码下面的问题是发现是错误的。
它找到密码并进入return true;
,但它继续运行。
如何退出递归并在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;
}
最佳答案
它应该是:
else if (Match...) return true;
甚至:
if (nextGuess == actualPassword || Match...)
return true;
因为您想在电流失败时继续迭代,如果发现问题则停止迭代。
关于c# - 如何退出递归,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40766705/