Re: ALgorithm Solution



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 ;
}
.



Relevant Pages

  • Re: nr of bits set to "1" in a byte
    ... So add the octal digits together to get base64 ... * more 4-bit fields containing junk (sums that are uninteresting). ...
    (comp.lang.c)
  • Re: Help a friend with some c code
    ... prototype in scope for 'SUMS'. ... Fix the prototype, and it will compile ... 'main' returns 'int'. ... this loop doesn't make any sense to me. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Optimal square calculation?
    ... Is any clever optimization possible when doing sums of squares? ... int sumOfSquares ... return iAcc; ...
    (comp.dsp)
  • Re: bitwise & operator and counting set bits
    ... > is set in the given variouble x. ... > int bit_count ... > ** The loop will execute once for each bit of x ... The final result being the sum of sums ...
    (comp.lang.c)
  • [C] erroneous fprintf output
    ... The exercise is to write a program that takes the sqrt of all ... integers 1-100 and separate them into two sets whose sums are ... int main ...
    (alt.comp.lang.learn.c-cpp)