i have a problem on iterative function and recursive function. i have a iterative function and i have to convert it into a recursive one. could you give me some advice on my code?thanks so much
the code is to determine if the array of data points correspond to a concave function using recursion.
Here is the code of the iterative version:
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;
}
And, here is the code of my recursive version which can't work:
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);
}
Not necessary the best/cleanest way, but you may replace any loop
for (int i = 0; i != N; ++i) {
body(i, localVars);
}
by
void body_rec(int N, int i, LocalVars& localVars)
{
if (i == N) return;
body(i, localvars);
body_rec(N, i + 1, localVars);
}
or
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);
}
So, in your case, you forget to pass slope
into the recursion.
[edit]
Full solution:
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);
}
Note also that the name seems "incorrect", you don't check if the "curve" is concave, case where delta == 0
should be specific I think...
In the iterative version of your program, the computation moves from 1 to n-1, but in the recursive version computation moves form n-1 to 1. So, instead of tail recursion, use head recursion. And slope should be static variable. So, declare slope as static variable. It will work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.