Created
April 7, 2015 15:01
-
-
Save bmccormack/74da33d6fba05248aaeb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct { | |
int *pArrNumbers; | |
long pSum; | |
int pos; | |
int len; | |
int (*funcMovingAvg)(void *self, int nextNum); | |
} MovingAvg; | |
int getMovingAvg(void *self, int nextNum) | |
{ | |
MovingAvg *ma = self; | |
// printf("pSum: %lu\n", ma->pSum); | |
// printf("nextNum: %d\n", nextNum); | |
// printf("ma->pos: %d\n", ma->pos); | |
// printf("ma->pArrNumbers[ma->pos]: %d\n", (ma->pArrNumbers)[(ma->pos)]); | |
ma->pSum = ma->pSum - ma->pArrNumbers[ma->pos] + nextNum; | |
ma->pArrNumbers[ma->pos] = nextNum; | |
ma->pos++; | |
if (ma->pos >= ma->len){ | |
ma->pos = 0; | |
} | |
return ma->pSum / ma->len; | |
} | |
MovingAvg *MovingAvg_new(int arrSize) | |
{ | |
MovingAvg *movingAvg = malloc(sizeof(MovingAvg)); | |
int *arrNumbers = calloc(arrSize, sizeof(int)); | |
movingAvg->pArrNumbers = arrNumbers; | |
movingAvg->pSum = 0; | |
movingAvg->pos = 0; | |
movingAvg->len = arrSize; | |
movingAvg->funcMovingAvg = getMovingAvg; | |
return movingAvg; | |
} | |
void MovingAvg_destroy(void *self) | |
{ | |
MovingAvg *ma = self; | |
if(ma) { | |
if(ma->pArrNumbers) free(ma->pArrNumbers); | |
free(ma); | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// a sample array of numbers. The represent "readings" from a sensor over time | |
int sample[] = {50, 10, 20, 18, 20, 100, 18, 10, 13, 500, 50, 40, 10}; | |
// the size of this array represents how many numbers will be used | |
// to calculate the average | |
int count = sizeof(sample) / sizeof(int); | |
int newAvg = 0; | |
MovingAvg *movingAvg = MovingAvg_new(10); | |
for(int i = 0; i < count; i++){ | |
newAvg = movingAvg->funcMovingAvg(movingAvg, sample[i]); | |
printf("The new average is %d\n", newAvg); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment