Module: DarvinFunctions
- Defined in:
- ext/darvin_functions.c
Class Method Summary collapse
-
.nkmax(varray) ⇒ Object
vself is a reference to the module or itself varray is a Ruby array.
Class Method Details
.nkmax(varray) ⇒ Object
vself is a reference to the module or itself
varray is a Ruby array
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'ext/darvin_functions.c', line 17 VALUE mDarvinFunctions_nkmax(VALUE vself, VALUE varray) { VALUE new_array; int i, j, trail, offset; long *tot; // total for specific interval long *maxTot; // current sum for (i-1) (void)vself; // silence unused variable warning if (NIL_P(varray) || RARRAY_LEN(varray) == 0) return varray; new_array = rb_ary_new2(RARRAY_LEN(varray)); tot = ALLOCA_N(long, RARRAY_LEN(varray)); // allocate memory maxTot = ALLOCA_N(long, RARRAY_LEN(varray)); // allocate memory trail = 0; // trailing value maxTot[0] = tot[0] = FIX2INT(RARRAY_PTR(varray)[0]); // need first total (for single cell average), seed for others /* * this loop initializes the totals for all slot averages (1-n) * assume numbers are 1 2 3 4 5 * maxTot[] will be 1, 3, 6, 10, 15 * The idea is each slot is initialized to the earliers total values, * that is slot0 is initialized to 1 * slot1 is initialized to 1 + 2 * ... * slot4 is initialized to 1 + 2 + 3 + 4 + 5 */ for (i=1; i<RARRAY_LEN(varray); i++) // loop thru all the numbers maxTot[i] = tot[i] = (tot[i-1] + FIX2INT(RARRAY_PTR(varray)[i])); // compute tot for subsequent cells (starting at cell 0) for (offset=1; offset<RARRAY_LEN(varray); offset++) { // loop starting at index 1 (index-1 is the value to subtract) trail = FIX2INT(RARRAY_PTR(varray)[offset-1]); // this is the value to subtract from the beginning of the list for (i=offset; i<RARRAY_LEN(varray); i++) { // first time subtract 1 from all (except n list) j = i - offset; // subtract trail and add next value tot[j] += (FIX2INT(RARRAY_PTR(varray)[i]) - trail); // to temp variable if (tot[j] > maxTot[j]) maxTot[j] = tot[j]; // set maxTot for slot if larger } } for (i=0; i<RARRAY_LEN(varray); i++) { rb_ary_push(new_array, INT2FIX(roundNumber((double)maxTot[i] / (double)(i+1)))); } return new_array; } |