I have an array of 10 elements, and I need to make that array into its moving average equivalent.

Using 3 elements each time (eg average of elements at indices 0-2, then 1-3 and so on up to indices from 10 then back to 0 and 1 to make the new array have exactly 10 elements as well).

What is the best approach to this without using pointers to wrap the array around (ring buffer).

有帮助吗?

解决方案

Just do some bounds checking and wrap the index in code.

The example code below can be made more efficient, but it's written like this for clarity (sort of). Also there may be some minor mistake since I'm typing into StackOverflow rather than compiling it.

int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int averages[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

for (int i = 0; i < 10; i++)
{
    int a = i;
    int b = i + 1 > 9 ? i - 10 + 1;
    int c = i + 2 > 9 ? i - 10 + 2;

    int count = array[a] + array[b] + array[c];
    int average = count / 3; // note this will truncate any decimal part

    averages[i] = average;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top