繁体   English   中英

将迭代函数转换为递归函数

[英]convert iterative function to recursive function

我对迭代函数和递归函数有问题。 我有一个迭代函数,我必须将其转换为递归函数。 您能给我一些有关我的代码的建议吗?非常感谢

该代码将使用递归确定数据点的数组是否对应于凹函数。

这是迭代版本的代码:

bool isConcave(double a[], int n)
{
int slope = 1;
bool concave = true;

for (int i = 1; i < n && concave; i++)
{
    double delta = a[i] - a[i-1];

    if (slope > 0)
    {
        if (delta < 0)
            slope = -1;
    }
    else if (delta > 0)  
        concave = false; // slope == -1 and delta > 0
}
return concave;
}

而且,这是我的递归版本的代码不起作用:

bool isConcave_r(double a[], int n, int& slope)  
{
//Implement this function using recursion
double delta = a[n] - a[n-1];
bool concave = true;

if (n == 0)
    return false;
if (slope > 0)
{
    if (delta < 0)
    {
        slope = -1;
    }
    else
        concave = true;
}else
    return 0;

//dummy return statement
return isConcave_r(a, n, slope);

}

不一定是最好/最干净的方法,但是您可以替换任何循环

for (int i = 0; i != N; ++i) {
    body(i, localVars);
}

通过

void body_rec(int N, int i, LocalVars& localVars)
{
    if (i == N) return;
    body(i, localvars);
    body_rec(N, i + 1, localVars);
}

要么

int body_rec(int N, int i, LocalVars& localVars)
{
    if (i == N) return localVars.res; // or any correct value
    body(i, localvars);
    if (localVars.end) { // break the "loop", and so stop the recursion.
        return localVars.res; // or any correct value
    }
    return body_rec(N, i + 1, localVars);
}

因此,在您的情况下,您忘记将slope传递给递归。

[编辑]

完整解决方案:

bool isConcave_r(int N, int i, double a[], int slope)
{
    if (i >= N) return true;

    const double delta = a[i] - a[i-1];

    if (slope > 0) {
        if (delta < 0) {
            slope = -1;
        }
    }
    else if (delta > 0) {
        return false;
    }
    return isConcave_r(N, i + 1, a, slope);
}

bool isConcave(double a[], int n)
{
    int i = 1;
    int slope = 1;
    return isConcave_r(n, i, a, slope);
}

另请注意,该名称似乎是“不正确的”,您不检查“曲线”是否为凹形,我认为delta == 0应该是特定的...

在程序的迭代版本中,计算从1移到n-1,但是在递归版本中,计算从n-1移到1。因此,请使用头递归代替尾递归。 并且斜率应该是静态变量。 因此,将斜率声明为静态变量。 会的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM