递归条件 - 缺少基本情况 [英] Recursive conditions - missing base case

查看:31
本文介绍了递归条件 - 缺少基本情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经把我的头脑围绕在递归上,现在正试图将它投入实际应用中,而不会出现堆栈溢出(或再次执行斐波那契数列!双关语.

I've wrapped my head around recursion, and am now trying to put it into into practical application without a stack overflow (or doing the Fibonacci sequence (again)! Pun intended.

在我的示例中,我循环遍历了一组相似的项目,直到有机会该元素是唯一的.任务完成.对于任何递归函数,您是否总是需要基本情况​​和递归情况和终止条件?我想不出这个例子的基本情况.

In my example I've looping over an array of similar items until by ransom chance the element is unique. Job done. Do you always need a base case AND recursive case AND termination conditions for any recursive function?? I can't think of a base case for this example.

var myArray = ["bananas", "bananas", "bananas", "bananas", "Gwen Stefani!"];

var tries = 0;
alert(getIt(myArray, tries));

function getIt(arr, num)
{
  r = Math.floor(Math.random()* arr.length);

  // Base case
  // something here??
  // but only if we don't need to call
  // the recursive function

  // termination case
  if (arr[r] != "bananas") 
    {
            alert("Found on attempt " + num);
        return arr[r];
    }

  // Recursive case
  return getIt(arr, num+1);
}

推荐答案

这取决于您使用的术语,但是 http://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Recursive_functions_and_algorithms(例如)具有基本情况和终止情况,含义相同.在您的代码中,终止情况是基本情况,因为它是产生结果的原因.

It depends on what terms you're using, but http://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Recursive_functions_and_algorithms (for example) has the base and terminating cases meaning the same thing. In your code, the termination case is the base case as it is what produces the result.

作为旁注,您可以这样做:

As a side note, you could do this:

alert(getIt(myArray, 0));

而不是这个:

var tries = 0;
alert(getIt(myArray, tries));

这篇关于递归条件 - 缺少基本情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆