我有一个我用PHP编写的函数的问题.如您所见,该函数使用自身返回值的数组.
public function getRepeat($day = "array")
{
if ($day == 'array')
{//Return an array with the repeated days as values
foreach (array(1,2,3,4,5,6,0) as $value)
{
if ($this->getRepeat($value))
{
$returnArray[] = $value;
}
}
return $returnArray;
}
else if (in_array($day, array(1,2,3,4,5,6,0) ))
{
if ($day == 1)
return $this->repeat1;
if ($day == 2)
return $this->repeat2;
if ($day == 3)
return $this->repeat3;
if ($day == 4)
return $this->repeat4;
if ($day == 5)
return $this->repeat5;
if ($day == 6)
return $this->repeat6;
if ($day == 0)
return $this->repeat0;
}
}
Run Code Online (Sandbox Code Playgroud)
一旦它自己调用每个变量就会变成无限循环.
是什么导致这个?
您必须始终考虑分两部分编写递归函数:
确保这两个规则保持应该导致递归函数,在输入有效的情况下终止该函数.
这是一个递归的解决方案 - 但它是在Java :)
public static void main(String[] args) {
List<Integer> testVals = new ArrayList<Integer>();
testVals.add(0);
testVals.add(1);
testVals.add(2);
testVals.add(3);
testVals.add(4);
testVals.add(5);
List<Integer> toMatch = new ArrayList<Integer>(testVals);
List<Integer> matches = new ArrayList<Integer>();
repeatRec(testVals, matches, toMatch);
System.out.println("Matches " + matches);
}
public static void repeatRec(List<Integer> toTest, List<Integer> matches, List<Integer> toMatch) {
if (toTest.isEmpty()) {
//we are done
return;
} else {
Integer head = toTest.get(0);
if (toMatch.contains(head)) {
matches.add(head);
}
//could have else here if we're only interested in the first match
repeatRec(toTest.subList(1, toTest.size()), matches, toMatch);
}
}
Run Code Online (Sandbox Code Playgroud)