Re: ALgorithm Solution
- From: Alan Johnson <alanwj@xxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 30 Mar 2006 13:41:52 -0800
yezi wrote:
Dear ALL :
I try to set up a simulation coding. THe formula I am with is like
SUMi (SUMj(SUMk(SUM..))) (Ai*Bj*Ck....)
Let n= number of sums.
THe problem is n is not fixed, which is really depend on the input
variable.
Now my question is how to develop such kind of algorithm. I can not
figure it out. Thanks for any comments.
Bin
You could express it recursively. Make a sums function that calls itself for each nested sum. Pass it a vector of all the bounds for each sum. It will also need to propagate the indices from the outer recursions so that the function can use them. In C this might look something like the following (Note: not tested extensively for correctness.).
Alan
/*
* a - the lower bounds for sums.
* b - the upper bounds for sums.
* x - array in which domain element is formed (initial values don't matter).
* i - current level of recursion.
* n - number of elements in a, b, x.
* f - the function the call.
*/
int sums(int a[], int b[], int x[], unsigned i, unsigned n, int (*f)(int *, unsigned))
{
int j, acc = 0 ;
if (i == n)
return f(x, n) ;
for (j = a[i]; j <= b[i]; ++j)
{
x[i] = j ;
acc += sums(a, b, x, i+1, n, f) ;
}
return acc ;
}
/* Multiply all the elements of x. */
int mult(int *x, unsigned n)
{
unsigned i ;
int acc = 1 ;
for (i = 0; i < n; ++i)
acc *= x[i] ;
return acc ;
}
/* Test program. */
#include <stdio.h>
int main()
{
int a[] = { 1, 2, 10 } ;
int b[] = { 5, 3, 15 } ;
int x[3] ;
printf("%i", sums(a, b, x, 0, 3, mult)) ;
return 0 ;
}
.
- References:
- ALgorithm Solution
- From: yezi
- ALgorithm Solution
- Prev by Date: Re: String concatenation design
- Next by Date: Re: returning lvalue in C vs C++
- Previous by thread: ALgorithm Solution
- Index(es):
Relevant Pages
|