'find barycenter with only one recursive call
My professor wrote us the code to find barycenter with only one recursive call. He said that the strategy was to propagate forward the value of sp (right sum), and propagate backwards the value ss (left sum), *b should be a parameter to indicate the position of barycenter.
int barRecAux( int a[], int i, int n, int sp, int * b ) {
int ss;
if ( i == n ) {
return 0;
}
sp += a[i];
ss = barRecAux( a, i + 1, n, sp, b );
if ( *b >= 0 ) {
return ss;
}
if ( ss == sp ) {
*b = i + 1;
return ss;
} else {
return ss + a[i];
}
}
int barycenRec( int a[], int n, int * k ) {
*k = -1;
barRecAux( a, 0, n, 0, k );
if ( *k < 0 ) {
return 0;
}
return 1;
}
The fact is that I don't understand how this code works, for example
what does *k=-1 mean? Should I consider the first recursive call as
barRecAux(a, 0, n, 0, -1)?
*k = -1;
barRecAux( a, 0, n, 0, k );
if ( *k < 0 ) {
return 0;
}
And what does this function do?
ss = barRecAux( a, i + 1, n, sp, b );
if ( *b >= 0 ) {
return ss;
}
And how can b be positive?
Can you give me an example of how the code works? maybe also written in a complete way in order to test it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
