簡體   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